2016-06-29 32 views
-1

我試圖按相關字段上的多個值進行排序,按鍵過濾,但運行第二個order_by排序,第一個過濾器,而不是最近的。Django按多個過濾的外鍵值排序

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的價值?

回答

1

我不確定這是否是您正在尋找的答案,但我會建議在產品表中添加評分和分數作爲產品屬性的外鍵,而不是相反。對我來說,這更像一個模型。

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


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

這你就可以很容易地順序使用:

order_by(score__value, rating__value) 

其他方式,我認爲產生太多不必要的工作,特別是如果你沒有太多的附加產品屬性。

+0

不幸的是,這不是一個真正的選擇。一個Product可以有30多種不同的'ProductAttribute',其中沒有一個是保證存在的。在我們的例子中'Product'是父項,'ProductAttribute'是子項。 – TorelTwiddler

+0

你的問題不是很清楚@TorelTwiddler這似乎是一個合法的答案根據我對你的問題的理解 – e4c5

+0

@ e4c5我不知道我怎麼能使它更清楚。這不是一個可以接受的答案,因爲我需要做出非常大量的更改(工作周)才能進行此更改。我不覺得說「改變你的前提」是解決問題的好辦法。 – TorelTwiddler