开发者

Django - Better evaluation of relationship at the model level

Here's a simple relational pair of models.

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

  def has_books(self):
    if Book.objects.filter(shelf=self):
      return True
    else:
      return Fals开发者_开发百科e

class Book(models.Model):
  shelf = models.ForeignKey(Shelf)
  name = models.CharField(max_length=100)

Is there a better (or alternative) way to write the "has_book" method?

I'm not a fan of the double database hit but I want to do this at the model level.


You can do:

def has_books(self):
    return self.book_set.all().count() > 0


I'm not sure what your objection is to the way Hassan has written it, but perhaps - based on your 'double database hit' comment - you're looking for a way of checking all Shelf instances at once? If so, you can do it with annotations:

from django.db.models import Count
Book.objects.all().annotate(num_books=Count('book')).filter(num_books__gt=0)

This gives you a list of all shelves with at least one book.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜