python - Get one related object in single request for Django ORM -
i have models
class book(models.model): title = models.charfield(max_length=255, blank=false, null=false) class like(models.model): user = models.foreignkey(user, related_name="like_user", blank=false, null=false) book = models.foreignkey(book, related_name="like_book", blank=false, null=false) class meta: unique_together = ["user", "book"]
i want books , check if current user liked each book in single request
book.objects.select_related('like_book').all()
won't work because of many results
book.objects.prefetch_related('like_book').all()
will cache like_set
contain likes book. not 1 user.
in end want have additional field is_liked
books = book.objects.magic_fetch('like_book', user=self.request.user).all() books[0].is_liked
* updated address comments *
so speaking, think use:
book.objects.annotate(is_liked=case(when(like__user=self.request.user, then=true), default=false))
Comments
Post a Comment