2017-08-25 4 views
0

フィルタ結果の配布方法は?私は、各parent_types 5人の服(「トップ」、「底部」、「靴」)を取得する(ジャンゴ)

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

私はそれを、より効率的な方法をやってみたいです。 (3つのフィルタは厄介です!)私はモデルを再設計する必要があり

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種類の合計が5種類であることを望んでいます。 – ikkuh

+0

@ikkuh回答を更新しました。 –

+2

@SancaKembangこれは、Johnソリューションのパフォーマンスよりも効率的ではありません。同じです – iklinac

関連する問題