【问题标题】:django in one queryset all and filter methodsdjango 在一个查询集中所有和过滤方法
【发布时间】:2018-07-27 14:29:23
【问题描述】:

我尝试在 django 应用程序中显示,查看最后 5 个项目以及将 is_home 设置为 True 的项目。

请提示这是否“好”和正确的方式:

我的模特:

class Event(models.Model):
    title = models.CharField(max_length=500)
    date = models.DateField()
    is_home = models.BooleanField(default=False)

查看我的查询:

context['event_list'] = Event.objects.filter(Q(Event.objects.all()) | Event.objects.filter(is_home=True))[:5]

【问题讨论】:

    标签: python django filter django-queryset


    【解决方案1】:
    context['event_list'] = Event.objects.filter(is_home=True).order_by(-id)[:5]
    

    【讨论】:

    • 我以为他想要最后五个项目所有项目,例如is_home=True
    • @Siegmeyer +1 是
    • @Siegmeyer 当我再次阅读他的问题时,您似乎是对的
    【解决方案2】:

    简单使用:

    list(Event.objects.all().order_by('-id')[:5]) + list(Event.objects.filter(is_home=True))
    

    不幸的是,您不能(据我所知)在获取切片后组合查询,因此必须转换为列表。

    如果你真的想要QuerySet,你可以这样做:

    Event.objects.filter(Q(id__in=Event.objects.all().order_by('-id')[:5].values_list('id', flat=True)) | Q(is_home=True))
    

    太丑了。

    【讨论】:

    • 非常感谢 :) +1
    猜你喜欢
    • 2013-01-31
    • 2018-09-22
    • 2017-12-05
    • 2020-08-22
    • 2019-04-15
    • 2011-09-29
    相关资源
    最近更新 更多