【问题标题】:.filter() on Django Unioned QuerySets gives incorrect resultsDjango Unioned QuerySets 上的 .filter() 给出不正确的结果
【发布时间】:2017-09-07 00:31:06
【问题描述】:

我有一个名为Event 的模型,它有一个startstop 字段,两者都是DateTimeField 类型。我想过滤掉 startstop 字段为空的事件。

使用这两个查询,我得到 2 个查询集:

tempset = Event.objects.filter(site__slug='test-site', owner__email='bill@email.com')
tempset2 = Event.objects.filter(site__slug='test-site', invite__slug='bill-compton')

我尝试过这样的联合:

tempset.union(tempset2)

还有这样的:

tempset = Event.objects.filter(site__slug='test-site', owner__email='bill@email.com').union(Event.objects.filter(site__slug='test-site', invite__slug='bill-compton'))

但是当我尝试过滤时,使用以下语法:

filtered_query = tempset.filter(start__isnull=False, stop__isnull=False)

然后打印出起始值和终止值,

for thing in filtered_query:
    print(thing.start, thing.stop)

我得到这个输出:

None None
2017-09-01 11:00:25+00:00 None
2017-09-03 11:00:00+00:00 2017-09-03 12:00:00+00:00
2017-09-06 11:00:00+00:00 2017-09-06 12:00:00+00:00
2017-09-06 11:00:54+00:00 2017-09-06 12:00:54+00:00
2017-09-06 11:00:07+00:00 2017-09-06 12:00:07+00:00

注意:

如果我使用| 字符来合并两个查询集,则此过滤查询可以正常工作。我的理解是 .union() 将允许这种合并行为。

有什么想法吗?

【问题讨论】:

    标签: django python-3.x django-models


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      尝试查看查询print(filtered_query.query)。最有可能的是,过滤不会添加到您的 QuerySet 中。也许这张票描述了同样的问题:https://code.djangoproject.com/ticket/28519

      据我了解,现在可以在合并之前过滤数据(如果您想完全使用UNION):

      filtered_query = (
          Event
          .objects
          .filter(site__slug='test-site', owner__email='bill@email.com', start__isnull=False, stop__isnull=False)
          .union(Event.objects.filter(site__slug='test-site', invite__slug='bill-compton', start__isnull=False, stop__isnull=False))
      )
      

      如果我使用 |字符来合并两个查询集,这个过滤 查询工作正常。

      | 将 QuerySets 的 WHERE 条件合并为单个 SELECT,但 .union() 合并了两个查询的结果(两个 SELECT)。比较两种变体的 SQL。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-27
        • 2017-12-14
        • 2019-03-12
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        相关资源
        最近更新 更多