Filter on prefetch_related in Django

后端 未结 3 841
太阳男子
太阳男子 2021-01-03 20:03

Is there a way of filtering prefetched objects? I need to get the latest() of the prefetched objects but prefetch_related doesn\'t work if you use latest because the query i

3条回答
  •  耶瑟儿~
    2021-01-03 20:48

    Yes, it can be done in this way :

    authors=Author.objects.prefetch_related('book_set')
    

    If you want to filter by an attribute(name) present in Author model you can simply filter it by writing:

    authors.filter(name='your_value')
    

    But if you want to apply filter on the Books model you have to write the following way:

    authors.filter(book__created__gt='your_date')
    

    This will filter all the books that have create date(created attribute in the Book module) greater than your date.

提交回复
热议问题