Django:按特定的多对一个值对行进行排序和过滤

时间:2018-01-10 04:03:45

标签: django postgresql

在提供的架构中,我想按照记录的特定RecordsAttribute进行排序。我想在原生的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'),)

我还需要按RecordsAttribute.value过滤Attribute.color

我可以更改架构,但上面的架构似乎最简单,可以代表我需要建模的内容。

我怎么能:

  • 查询Records Attribute.color 'red'的所有Attribute.value,例如10 Records
  • 查询所有Attribute.value,并按Attribute Attribute.color 'red'所关联的color的{​​{1}}排序。

**我已将其简化为上述内容 - 实际上ForeignKey字段为AttributeDefinition到{{1}},但我认为这并不重要现在。

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)

希望这有帮助!