Django distinct和order_by、annotate不起作用
我有两张桌子Django distinct和order_by、annotate不起作用,django,django-models,Django,Django Models,我有两张桌子 class A(models.Model): A_version = models.DecimalField(max_digits=4, decimal_places=0) A_name = models.CharField(max_length=32, blank=True) A_type = models.CharField(max_length=32, blank=True) unique_together(A_version,A_nam
class A(models.Model):
A_version = models.DecimalField(max_digits=4, decimal_places=0)
A_name = models.CharField(max_length=32, blank=True)
A_type = models.CharField(max_length=32, blank=True)
unique_together(A_version,A_name)
class B(models.Model):
B_version = models.ForeignKey(A)
B_name = models.ForeignKey(A)
last_reported_time= models.DecimalField(max_digits=4, decimal_places=0)
unique_together(B_version,B_name)
obj = B.objects.filter(B_name__A_type="Vendor").
values('B_name','B_version').annotate(Max('last_reported_time')).
order_by('B_name','B.B_version')
上次报告的不是唯一的
现在我有两个问题
当我使用distinct
而不是annotate
时,我无法获得不同的值。所以我使用了一些人建议的annotate
。但我还是得到了非不同的值。如何获得不同的值
如果我查看上述查询的原始sql查询,它将被翻译成order\u by(B.B\u名称和A.B\u版本)
。如何通过(B.B\U版本)
获取订单
正如我在之前回答您的问题时提到的,这不是一个好的模型设计。由于A类中的A_名称和A_版本是唯一的,因此您应该在B类中使用外键来引用A类的ID。如果您这样做了,您的所有查询将更容易,因此您不必在此处发布所有这些问题 这是最后一次。删除类别B中的名称和版本外键:
class A(models.Model):
A_version = models.DecimalField(max_digits=4, decimal_places=0)
A_name = models.CharField(max_length=32, blank=True)
A_type = models.CharField(max_length=32, blank=True)
class Meta:
unique_together(A_version,A_name)
class B(models.Model):
a = models.ForeignKey(A) #Reference the A.id
last_reported_time= models.DecimalField(max_digits=4, decimal_places=0)
obj = A.objects.filter(A_type="Vendor").annotate(last_time=Max('B__last_reported_time')).
order_by('A_name','A_version')
更新:由于无法更改模型,请尝试以下操作:
class A(models.Model):
A_version = models.DecimalField(max_digits=4, decimal_places=0)
A_name = models.CharField(max_length=32, blank=True)
A_type = models.CharField(max_length=32, blank=True)
unique_together(A_version,A_name)
class B(models.Model):
B_version = models.ForeignKey(A, to_field='A_version') #Note the to_field
B_name = models.ForeignKey(A, to_field='A_name') #Note the to_field
last_reported_time= models.DecimalField(max_digits=4, decimal_places=0)
unique_together(B_version,B_name)
obj = A.objects.filter(A_type="Vendor").
values('A_name','A_version').annotate(last_time=Max('B__last_reported_time')).
order_by('A_name','A_version')
您可能应该清理示例代码,因为它似乎无法编译。1) Model
A
有两个名称相似的字段;2) unique\u一起
行引用不存在的字段;3) 我不熟悉上次报告的呼叫:它做什么?;4) B
模型使用与A
模型相同的字段名,这一事实也相当令人困惑。更新内容可能会获得更多的响应。jro抱歉,当时很匆忙。我现在已经编辑了代码,我现在已经回复了,但是当我查看您的模型时,我认为您需要解释模型A和模型B应该具有哪些功能。你想用你的模型做什么?米凯尔,事实上我不能改变模型。它已经由其他人设计,不应该以任何方式修改它。我不能删除外键,也不能插入任何属性。我应该检索表B中具有特定a_类型的所有不同数据,并按名称和版本对它们进行排序。我已经用一个新的建议更新了我的答复。我自己还没能测试这个,所以试一试,让我知道它是否有效。Mikael,我不能使用to_字段,因为它告诉B_版本应该有唯一设置为True,我不能这样做。我用“in”来连接表,现在它可以工作了