Django - Better evaluation of relationship at the model level

Posted by Brant on Stack Overflow See other posts from Stack Overflow or by Brant
Published on 2010-05-18T15:58:41Z Indexed on 2010/05/18 16:01 UTC
Read the original article Hit count: 328

Filed under:
|

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 False

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.

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models