首页 > 解决方案 > django 在 values_list 之后获取原始对象

问题描述

我的学生模型:

class Student(Person):
  father = models.ForeignKey('Person', on_delete=models.SET_NULL, blank=True, 
      null=True,related_name='student_father',help_text=_('Father'))
  mother = models.ForeignKey('Person', on_delete=models.SET_NULL, blank=True, 
           null=True,related_name=_('student_mother'),help_text=_('Mother'))
  classroom = models.IntegerField(ClassRoom.choices(), null=True, blank=True, 
           help_text=_('Classroom'))
 ..and some other fields

我想根据“name”、“father”、“mother”字段获取重复对象。我找到了 values_list('name'、'mother'、'father') 的重复对象,但我无法通过这种方式。如果我将 id 字段添加到 values_list 方法中找不到重复的对象。

Student.objects.values('name', 'father', 'mother').annotate(Count('name')).order_by().filter(name__count__gt=1)

在这个查询之后,我需要学生对象的 id。

标签: django

解决方案


你试图做的事情没有意义。

您正在聚合许多记录,然后只查找其中一个聚合对象的 PK。

考虑名称“Bill”存在于 8 条记录中的场景。您希望返回哪个 PK,哪个记录?

您需要执行第二次查询,以获取具有重复名称的对象的 PK:

names_list = Student.objects.values('name', 'father', 'mother').annotate(Count('name')).order_by().filter(name__count__gt=1)
for names in names_list:
    duplicates = Student.objects.filter(name=names.name)
    for dup in duplicates:
        print dup.pk

推荐阅读