filter foreign key object field in django code example
Example: how to filter queryset with foreign key in django
class BookedEvent(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
event = models.ForeignKey(Events, on_delete=models.CASCADE)
import django_filters
class BookedEventFilter(django_filters.FilterSet):
class Meta:
model = BookedEvent
fields = ['event__eventName', 'event__startDate','event__endDate','event__address']
def booked_event_page_view(request):
currentUser = request.user
bookedEvents = models.BookedEvent.objects.filter(user=currentUser)
filter = BookedEventFilter(request.GET, queryset=bookedEvents)
bookedEvents = filter.qs
context = {'bookedEvents': bookedEvents, 'filter':filter}
return render(request, 'booked_events.html', context)