📜  过滤外国文件 django_filters - Python 代码示例

📅  最后修改于: 2022-03-11 14:46:28.784000             🧑  作者: Mango

代码示例1
# *********** 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)