user3111525
user3111525

Reputation: 151

Django remove duplicates from queryset

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?

Upvotes: 9

Views: 15949

Answers (2)

pcoronel
pcoronel

Reputation: 3981

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

Upvotes: 14

Dmitry Loparev
Dmitry Loparev

Reputation: 462

To reference fields of model in filtering you can use Django ORM F function: https://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model

But i guess you cannot delete one of them :) You got to decide which one you want to delete

UPDATE

Look when you filter like Object.objects.filter(photo__name='something') you filter Object table by related photo name. So you dealing with join over two tables. If you want to exclude objects with name = related photo name you should do something like this

from django.db.models import F
Object.objects.exclude(name=F('photo__name'))

Is that useful?

Upvotes: 0

Related Questions