【问题标题】:How to distribute the filter result? (Django)如何分配过滤结果? (姜戈)
【发布时间】:2017-08-25 08:44:42
【问题描述】:

我想为每个 parent_types(“top”、“bottom”、“shoes”)检索 5 件衣服

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

我应该重新设计模型吗?我应该将“类型”字段排除在类中吗?还是不可能?

【问题讨论】:

    标签: django django-models django-views django-queryset


    【解决方案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')
    

    【讨论】:

    • 他想要每种类型的 5 个,而不是总共 5 个。
    • 你也可以重写我的模型。你可以将Type添加为另一个类??嗯
    • type 设置为选项,您的解决方案可能会奏效。但我只是想如果将type 设置为ManyToMany,我可能会有更好的性能,尤其是在这种情况下。我只是猜测:P
    • 我还不知道,但是你可以用这个chrome extention来比较性能也可以this article...
    猜你喜欢
    • 2011-10-15
    • 2020-11-06
    • 2011-02-27
    • 2011-01-27
    • 1970-01-01
    • 2017-08-30
    • 2020-08-17
    • 2019-08-02
    • 2021-03-14
    相关资源
    最近更新 更多