django - 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。
解决方案
你试图做的事情没有意义。
您正在聚合许多记录,然后只查找其中一个聚合对象的 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
推荐阅读
- hybris - 更改 hybris 后台高级搜索中附加属性选择器的位置
- java - 如何使用aws java异步客户端耗尽所有结果
- objective-c - 当网络发生变化时,文件下载有时会从头开始(AFURLSessionManager)
- reactjs - 在反应响应轮播中消失轮播图像的任何方法?
- php - 一旦单击其中的表单中的提交按钮并且该表单未处理,则使用 ajax 打开的模态框就会关闭
- spss - SPSS 倾向得分匹配多个控制
- java - 如何在 JAVA (Amazon S3) 中使用“阻止公共访问”设置?
- docusignapi - 我如何使用刷新令牌在 docusign 中获取新的访问令牌
- nat - NAT 会改变传出流量的目的地吗?
- clojure - 为什么 Clojure 中这两个函数的输出不同?