Django从查询中删除重复项

2024-04-24 02:43:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想删除相对字段中的重复项,我的queryset示例:

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

if name == photo__name and url == photo_url我需要删除其中一个,如何使用Django ORM进行此操作,或者需要遍历queryset?


Tags: anddjangonameurl示例ifobjectsobject
2条回答

要在筛选中引用模型字段,可以使用Django ORMF函数:https://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model

但是我想你不能删除其中的一个

更新

当你像Object.objects.filter(photo__name='something')那样过滤时,你会根据相关的照片名过滤对象表。所以你要处理两张桌子的连接。如果要排除名为“相关照片名”的对象,应执行以下操作

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

这有用吗?

如果您使用的是PostgreSQL,请查看Django docs on ^{}

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.

因此,在您的示例中,可以使用以下方法删除某些字段上的重复项:

.order_by('photo__name', 'photo__url').distinct('photo__name', 'photo__url')

相关问题 更多 >