Django通过多个过滤的外键值排序



我正试图按相关字段上的多个值排序,由一个键过滤,但运行第二个order_by是由第一个过滤器排序,而不是最近的。

class Product(Model):
    name = CharField()

class ProductAttribute(Model):
    product = ForeignKey(Product)
    key = CharField()
    value = FloatField()

# This line sorts products as expected over the `ProductAttribute`s with a key of 'score'
products = Product.objects.filter(productattribute_set__key='score')
                          .order_by('productattribute_set__value')
# This line sorts products as expected over the `ProductAttribute`s with a key of 'rating'
products = Product.objects.filter(productattribute_set__key='rating')
                          .order_by('productattribute_set__value')
# This line sorts products based on score only, not on rating, then score (or vise versa)
products = Product.objects.filter(productattribute_set__key='score')
                          .order_by('productattribute_set__value')
                          .filter(productattribute_set__key='rating')
                          .order_by('productattribute_set__value')

是否有先按score的值排序,再按rating的值排序的方法?

我不确定这是否是您正在寻找的那种答案,但我建议将评级和分数作为产品属性的外键添加到您的Product表中,而不是相反。对我来说,这作为一个模型更有意义。

class Product(Model):
    name = CharField()
    score = ForeignKey(ProductAttribute)
    rating = ForeignKey(ProductAttribute)

class ProductAttribute(Model):
    key = CharField()
    value = FloatField()

您可以使用以下命令轻松订购:

order_by(score__value, rating__value)

我认为另一种方法会产生太多不必要的工作,特别是如果你没有太多额外的产品属性。

最新更新