2017-08-25 108 views
0

我想檢索5件衣服每個parent_types( 「頂」, 「底」, 「鞋」)如何分配過濾結果? (Django的)

user.clothes_set.filter(type="top")[:5] 
user.clothes_set.filter(type="bottom")[:5] 
user.clothes_set.filter(type="shoes")[:5] 

我想這樣做更有效的方式。 (三濾是討厭!)

top, bottom, shoes = user.clothes_set.filter(~~~) <- retrieve `5 items each` 

這裏有望布模型

class Clothes(models.Model): 
    id 
    type =  # top, bottom and shoes 
    owner = ForeignField # some one who post 

我應該重新設計的模型?我應該排除「類型」字段類?還是不可能?

回答

1

這樣的事情?

user.clothes_set.filter(type__in=['top', 'bottom', 'shoes'])[:5] 

更新:由於下面的評論;

offset = lambda t: user.clothes_set.filter(type=t)[:5] 
top, bottom, shoes = offset('top'), offset('bottom'), offset('shoes') 
+2

他希望每個類型中的5個不總是5個。 – ikkuh

+0

@ikkuh我更新了答案.. –

+2

@SancaKembang這不是以比John解決方案更高效的方式表現明智,它是相同的 – iklinac