12. 查找具有重复字段值的行

_images/usertable2.png

假设您希望first_name与其他用户匹配的所有用户。

You can find duplicate records using the technique below.

>>> duplicates = User.objects.values(
    'first_name'
    ).annotate(name_count=Count('first_name')).filter(name_count__gt=1)
>>> duplicates
<QuerySet [{'first_name': 'John', 'name_count': 3}]>

如果您需要填写所有记录,您可以这样做

>>> records = User.objects.filter(first_name__in=[item['first_name'] for item in duplicates])
>>> print([item.id for item in records])
[2, 11, 13]