Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 349
Lujeni Avatar asked Dec 30 '25 14:12

Lujeni


1 Answers

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'))
like image 51
Daniel Roseman Avatar answered Jan 02 '26 11:01

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!