Filter on prefetch_related in Django

六月ゝ 毕业季﹏ 提交于 2019-12-12 08:18:59

问题


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 is changed?

The example here does what I need but I was hoping there's a simpler workaround...

https://github.com/ionelmc/django-prefetch#example


回答1:


As of Django 1.7, filtering prefetched objects is possible. See this SO answer, and the Django documentation.




回答2:


It is very simple method which is hardly comparable with those app, but hope you will find it useful:

class Author(models.Model):
    name = models.CharField(max_length=100)

    def latest_book(self):
        return max(self.book_set.all(), key=lambda book: book.created)

authors = Author.objects.prefetch_related('book_set')
authors[0].latest_book() #  what you wanted



回答3:


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.



来源:https://stackoverflow.com/questions/10915319/filter-on-prefetch-related-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!