2017-08-25 102 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