在提供的架构中,我想按照记录的特定Records
对Attribute
进行排序。我想在原生的Django中这样做。
示例:
查询所有Records
(无论Attribute.color
),但按Attribute.value
排序,其中Attribute.color
为'red'
。显然Records
错过了'red
&#39} Attribute
无法排序,因此可以将其解释为NULL
或发送到最后。
每个Record
保证具有特定颜色的Attribute
中的一个或零(由unique_together
强制执行)。鉴于这是一对多的关系,Record
可以有Attributes
多于一种颜色。
class Record(Model):
pass
class Attribute(Model):
color = CharField() # **See note below
value = IntegerField()
record = ForeignKey(Record)
class Meta:
unique_together = (('color', 'record'),)
我还需要按Records
和Attribute.value
过滤Attribute.color
。
我可以更改架构,但上面的架构似乎最简单,可以代表我需要建模的内容。
我怎么能:
Records
Attribute.color
'red'
的所有Attribute.value
,例如10
Records
Attribute.value
,并按Attribute
Attribute.color
'red'
所关联的color
的{{1}}排序。 **我已将其简化为上述内容 - 实际上ForeignKey
字段为AttributeDefinition
到{{1}},但我认为这并不重要现在。
答案 0 :(得分:1)
我认为这样的事情会起作用:
record_ids = Attribute.objects.filter(color='red', value=10).values_list('record', flat=True)
和
record_ids = Attribute.objects.filter(color='red').order_by('value').values_list('record', flat=True)
这将为您提供记录ID。然后,你可以这样做:
records = Record.objects.filter(id__in=record_ids)
希望这有帮助!