user695652
user695652

Reputation: 4275

django model: sort queryset according to ForeignKey attribute

Hi I have the following 1:n relation involving A and B and I would like to get a queryset containing all objects of A ordered by the newest date which the corresponding B objects have.

class A(models.Model):
    ...


class B(models.Model):
    a = ForeignKey(B)
    date_created = models.DateTimeField()

Example:

A = {a1, a2}

B = {b1 = (a1, 2.4.), b2 = (a1, 1.5.), b3 = (a2, 7.9.), b4 = (a2, 1.1.)}

then a2 should be listed before a1 because b3 is newer than the newest date of b1 and b2.

Does anybody know how to do this in django?

Upvotes: 0

Views: 71

Answers (1)

dani herrera
dani herrera

Reputation: 51745

You should use annotate. See this sample:

Book.objects.annotate(num_authors=Count('authors')).order_by('num_authors')

For your code

from django.db.models import Max
your_query_set = (
    A
   .objects
   .annotate( max_data = Max( 'b__date_created' ) )
   .order_by( '-max_data' )
    )

Upvotes: 1

Related Questions