I'm bamboozled by Django aggregation:
https://docs.djangoproject.com/en/1.11/topics/db/aggregation/
I'd like to add a little to the example they present to clarify
my problem (keeping it in familiar territory with regards to the
documentation):
from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() country = models.ForeignKey('Country') class Country(models.Model): name = models.CharField(max_length=100) 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()
countries = Country.objects.prefetch_related(
Prefetch('author_set',
queryset=(Author.objects
.filter(book_set__pubdate__lte=SOMEDATE)
.annotate(last_publish=Max('book_set__pubdate'))
.order_by('-last_publish')
),
to_attr='authors'
)
)
#usage
for country in countries:
#get the first author in authors or None if empty
top_author = next(iter(country.authors), None)
authors = Author.objects.filter(
book__pubdate=Subquery(
(Author.objects
.filter(country=OuterRef('country'))
.values('country')
.annotate(max_date=Max('book_set__pubdate'))
.values('max_date')[:1]
)
)
)
1. Should this not be book_set__pubdate? Author has no book field, but wins a book_set field authors field of Book.
2. How can this subquery combine with the constraint that book_set__pubdate__lte=SOMEDATE? That is, I'd be interested in finding the latest before a given date and double whammy. Is it as simple as adding it as per:
authors = Author.objects.filter(
book__pubdate=Subquery(
(Author.objects
.filter(
country=OuterRef('country'),
book__pubdate__lte=date.today(),
)
.values('country')
.annotate(max_date=Max('book__pubdate'))
.values('max_date')[:1]
), output_field=models.DateField()
)
)
-- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com. To post to this group, send email to django...@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/c7ee7f3f-b20b-46ad-82b2-00d9b9b8b332%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.