31
As of Django 1.7, filtering prefetched objects is possible. See this SO answer, and the Django documentation.
7
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
- [Django]-How to delete a record in Django models?
- [Django]-Project design / FS layout for large django projects
- [Django]-Django celery task: Newly created model DoesNotExist
-1
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.
- [Django]-How to use csrf_token in Django RESTful API and React?
- [Django]-Attempt to write a readonly database – Django w/ SELinux error
- [Django]-Dynamically limiting queryset of related field
Source:stackexchange.com