# *********** 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)
Here is what the above code is Doing:
1. We are creating a BookedEventFilter class that inherits from django_filters.FilterSet.
2. We are specifying the model that we want to filter and the fields that we want to filter on.
3. We are creating a view that gets the queryset of all the BookedEvents for the current user.
4. We are creating a filter object using the BookedEventFilter class and passing in the queryset and the request.GET object.
5. We are setting the queryset of the view to the queryset that is returned from the filter object.
6. We are passing the filter object into the context so that we can use it in the template.
7. We are rendering the template with the context.