2

In the following example from django documentation, how to get

Publisher.objects.all()

annotated with field average_rating computed using average of book ratings and max_rating computed using maximum rating of books?

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()

class Publisher(models.Model):
    name = models.CharField(max_length=300)
    num_awards = models.IntegerField()

class Book(models.Model):
    name = models.CharField(max_length=300)
    pages = models.IntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    rating = models.FloatField()
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    pubdate = models.DateField()

class Store(models.Model):
    name = models.CharField(max_length=300)
    books = models.ManyToManyField(Book)
    registered_users = models.PositiveIntegerField()

Precisely I should be able to print something like this after the queryset:

for p in Publisher.objects.all().annotate(...):
    print p, p.average_rating, p.max_rating
0

1 Answer 1

1

You can access books of publisher using book__rating like this:

Publisher.objects.annotate(average_rating=Avg('book__rating'), max_rating=Max('book__rating'))
Sign up to request clarification or add additional context in comments.

1 Comment

FieldError: Cannot resolve keyword 'books_set' into field. Choices are: book, id, name, num_awards

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.