Salvatore Iovene
Salvatore Iovene

Reputation: 2323

Django ORM: how do I count objects that have the same properties?

I want to use the Django ORM to find instances in my models that have some of the same properties.

For instance, given this model:

class Person(Model):
  name = CharField()
  age = IntegerField()
  gender = CharField()

how can I find all persons that don't have a unique age and gender?

For instance given the following data:

 John 20 M
  Bob 21 M
Diana 20 F
Janet 20 F

I want a query that would return Diana and Janet.

Thanks!

EDIT: this seems to be a duplicate of Django Query where one field is duplicate and another is different

Upvotes: 3

Views: 266

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477200

You can work with a subquery and filter such that there is at least one other Person with the same name:

from django.db.models import Exists, OuterRef

Person.objects.filter(
    Exists(
        Person.objects.exclude(
            pk=OuterRef('pk')
        ).filter(age=OuterRef('age'), gender=OuterRef('gender'))
    )
)

Upvotes: 3

Related Questions