Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django remove duplicates from queryset

Tags:

python

orm

django

i want to remove duplicates in relative fields, my queryset example:

example = models.Object.objects.values('name', 'photo__name', 'url', 'photo__url').distinct()

if name == photo__name and url == photo_url i need to delete one of them, how can i do this with Django ORM or i need to iterate through queryset?

like image 940
user3111525 Avatar asked May 12 '14 10:05

user3111525


1 Answers

If you are using PostgreSQL, check out the Django docs on distinct():

On PostgreSQL only, you can pass positional arguments (*fields) in order to specify the names of fields to which the DISTINCT should apply...

When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.

Thus, in your example, you can remove duplicates on certain fields by using:

.order_by('photo__name', 'photo__url').distinct('photo__name', 'photo__url')
like image 83
pcoronel Avatar answered Oct 20 '22 04:10

pcoronel