doniyor
doniyor

Reputation: 37856

django - get latest object with model method in template

I have a model with method.

class Book(models.Model):
  title = models.TextField() 

class Review(models.Model):
  content = models.TextField()
  book = models.ForeignKey(Book,related_name="book_reviews")  

  def lastreview(self):
    return self.objects.order_by('-id')[:1]

but once I use this method in template

{{book.book_reviews.lastreview.content}}

it is showing nothing..

what am i missing here?

Upvotes: 0

Views: 672

Answers (1)

arocks
arocks

Reputation: 2882

I believe you are trying to retrieve the latest review of a book (which was not clear from your question). The related reviews for a book can be accessed by book.book_reviews. It is a QuerySet rather than a single Review object, hence {{ book.book_reviews.lastreview }} will fail.

I would recommend moving the lastreview method directly under Book, like:

class Book(models.Model):
    title = models.TextField()

    def lastreview(self):
        try:
            return self.book_reviews.order_by('-id')[0]
        except IndexError:
            return None

Now you can access the latest review of a book in your template by

{{ book.lastreview.content }}

Note: I recommend adding a DateTimeField to Review, as finding the latest review based on id can be misleading. For e.g., someone can edit an old review and it will not be shown as the latest.

Upvotes: 3

Related Questions