2017-06-30 94 views
0

我想合并这两个QuerySets。 HotkeyAndPrefix没有all_collections中每个Collection的条目。这意味着len(all_collections)> = len(all_collections_hotkeys_and_prefixes)。我怎样才能合并这两个QuerySets?如果在HotkeyAndPrefix中没有找到一个集合的entrie,我想hotkey = None,prefix = None。我可以在一个查询中实现吗?Django合并两个查询集

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) 
+0

不应该在'HotkeyAndPrefix'中使用'Collection'参数的'user'值应该是多少? – badiya

+0

这是创建集合的人员(管理员)的价值。 admin = User.objects.filter(username ='admin')[0] – seeberg

+0

你打算如何合并两个不同类型的对象的查询集?合并会给出什么样的新信息? – badiya

回答

2

您需要使用exclude()查询。您可以使用

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

走哪都在 HotkeyAndPrefix.objects.filter(assigned_collection__in=all_collections, user=current_user)查询集

值的列表,你可以过滤掉的价值,而不是在all_collections_hotkeys_and_prefixes_values多一个查询

all_collections_hotkeys_and_prefixes_excluded = all_collections.exclude(pk__in=all_collections_hotkeys_and_prefixes_values)

现在您有两个查询集,一个用户拥有热键/前缀的集合和另一个用户没有为其设置的集合