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

3👍

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'))
    )
)

Leave a comment