how to filter queryset with foreign key in django code example

Example: how to filter queryset with foreign key in django

# *********** how to filter queryset with django foreign keys **********

# in models.py file
class BookedEvent(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    event = models.ForeignKey(Events, on_delete=models.CASCADE)

    
# in filters.py file
import django_filters
class BookedEventFilter(django_filters.FilterSet):
    class Meta:
        model = BookedEvent
        #use __ (double underscore) to target foreign key values
        fields = ['event__eventName', 'event__startDate','event__endDate','event__address']   

        
# in views.py file 
def booked_event_page_view(request):
   # getting queryset
    currentUser = request.user
    bookedEvents = models.BookedEvent.objects.filter(user=currentUser)
    # adding event filter
    filter = BookedEventFilter(request.GET, queryset=bookedEvents)
    bookedEvents = filter.qs
    context = {'bookedEvents': bookedEvents, 'filter':filter}
    return render(request, 'booked_events.html', context)

Tags:

Misc Example