【问题标题】:Django merge two QuerySetsDjango 合并两个查询集
【发布时间】:2017-12-04 04:10:22
【问题描述】:

我想合并这两个查询集。 HotkeyAndPrefix 在 all_collections 中没有每个 Collection 的条目。这意味着 len(all_collections) >= len(all_collections_hotkeys_and_prefixes)。我如何合并这两个查询集?如果在 HotkeyAndPrefix 中找不到集合的条目,我希望 hotkey = None,prefix=None。我可以在一个查询中实现这一点吗?

models.py:

class Collection(models.Model):
    creator = models.ForeignKey(User, blank=True, null=True)
    ...

class HotkeyAndPrefix(models.Model):
    user = models.ForeignKey(User, null=True)
    assigned_collection = models.ForeignKey(Collection, null=True)
    hotkey = models.CharField(max_length=1, blank=True, null=True)
    prefix = models.CharField(max_length=20, blank=True, null=True)

    class Meta:
        unique_together = ('user', 'assigned_collection')

view.py

admin = User.objects.filter(username='admin')[0]
all_collections = Collection.objects.filter(creator=admin)
current_user = request.user
all_collections_hotkeys_and_prefixes = HotkeyAndPrefix.objects.filter(assigned_collection__in=all_collections, user=current_user)

【问题讨论】:

  • 对于不在HotkeyAndPrefix 中的Collection条目,user 的值应该是多少?
  • 这是来自创建集合的人(管理员)的值。 admin = User.objects.filter(username='admin')[0]
  • 你打算如何合并两个不同类型对象的查询集?合并会带来哪些新信息?
  • 我想在一个表中输出 all_collections,如果当前用户为一个集合定义了一个热键/前缀,我想在同一个表行中输出它。
  • 我认为你可以做的是输出两组,一组用户有热键/前缀,另一组用户没有。

标签: django django-queryset


【解决方案1】:

您需要使用exclude() 查询。您可以获取其中的值列表 HotkeyAndPrefix.objects.filter(assigned_collection__in=all_collections, user=current_user)查询集

使用

all_collections_hotkeys_and_prefixes_values = all_collections_hotkeys_and_prefixes.values_list('assigned_collection',flat=True)

您可以过滤掉该值,而不是在all_collections_hotkeys_and_prefixes_values 中再进行一次查询

all_collections_hotkeys_and_prefixes_excluded = all_collections.exclude(pk__in=all_collections_hotkeys_and_prefixes_values)

现在您有两个查询集,一个是用户有热键/前缀的集合,另一个是用户没有的集合

【讨论】:

    猜你喜欢
    • 2019-08-11
    • 1970-01-01
    • 2021-11-10
    • 2014-02-23
    • 2010-10-17
    • 2013-09-06
    • 2023-03-14
    • 2018-01-17
    • 2013-02-22
    相关资源
    最近更新 更多