Categories
Python Answers

How to select only rows with duplicate field values with Python Django?

Spread the love

Sometimes, we want to select only rows with duplicate field values with Python Django.

In this article, we’ll look at how to select only rows with duplicate field values with Python Django.

How to select only rows with duplicate field values with Python Django?

To select only rows with duplicate field values with Python Django, we can use the filter method.

For instance, we write

from django.db.models import Count

Literal.objects.values('name')
               .annotate(Count('id')) 
               .order_by()
               .filter(id__count__gt=1)

to call annotate with Count('id') to aggregate the rows with the same id value.

And then we call filter with the id__count__gt set to 1 to get the aggregate rows with the id count larger than 1.

Conclusion

To select only rows with duplicate field values with Python Django, we can use the filter method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *