Lujeni
Lujeni

Reputation: 356

Annotate a count of a related field

django: 1.5.5

I need to order domains by the number of rentals.

models:

class Rental(models.Model):
    ...

class Domain(models.Model):
    ...


class RentalExtraBase(models.Model):
    rental = models.ForeignKey(Rental, unique=True, related_name='extras')

    class Meta:
       abstract = True


class RentalExtra(RentalExtraBase):
    domain = models.ForeignKey(Domain)

query:

from django.db.models import Count
Domain.objects.all().annotate(rentalextra_set_count=Count('rentalextra_set'))

however it's seems to be impossible using this field. I tried with a specific related_name without success.

error:

FieldError: Cannot resolve keyword 'rentalextra_set' into field ... (list of the Domain fields without rentalextra or rentalextra_set)

Any idea?

Regard

Upvotes: 3

Views: 417

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599450

You just use the lower-case name of the related model, as you do when following a relationship backwards in a query:

Domain.objects.all().annotate(rentalextra_set_count=Count('rentalextra'))

Upvotes: 3

Related Questions