FunLovinCoder
FunLovinCoder

Reputation: 7897

Django: list all objects with non unique field

If I have the following Model:

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

how do I list all objects that have a non unique last_name field? For example, if there are 20 objects that all have the last_name 'Smith', they would be listed. However, if only one object had the last_name 'Euler' it would not be included in the list.

Upvotes: 2

Views: 1599

Answers (2)

Alexander
Alexander

Reputation: 51

You will probably want to cast list to non_unique_last_names to fight OperationalError: sub-select returns 2 columns - expected 1

So, to those who will use this code, the right version is:

from django.db.models import Count
non_unique_last_names = (Person.objects
    .values_list('last_name', flat=True)
    .annotate(last_name_count=Count('last_name'))
    .filter(last_name_count__gt=1))

non_unique_person_objects = Person.objects.filter(last_name__in=list(non_unique_last_names))

Upvotes: 5

Here's one way with 2 queries:

non_unique_last_names = (Person.objects
    .values_list('last_name', flat=True)
    .annotate(last_name_count=Count('last_name'))
    .filter(last_name_count__gt=1))

non_unique_person_objects = Person.objects.filter(last_name__in=non_unique_last_names)

Upvotes: 6

Related Questions