正如标题所示,我有多组查询,每组查询都返回一个值列表。然后,我使用值列表来过滤另一个查询集。目前,我只能一次执行一个查询集的第二步。是否可以将我的初始值列表组合成一个超长列表?我正在尝试创建类似功能的活动/新闻提要。
views.py:
cookie_ids = Cookie.objects.filter(board__pk=self.kwargs['pk']).values_list('id',
flat=True)
sugar_ids = Sugar.objects.filter(board__pk=self.kwargs['pk']).values_list('id',
flat=True)
**then:
context['cookie_actions'] = Action.objects.filter(target_id__in=cookie_ids)
context['sugar_actions'] = Action.objects.filter(target_id__in=sugar_ids)
编辑:我认为这是唯一可能重要的模型
Models.py:
class Action(models.Model):
user = models.ForeignKey(User,
related_name='actions',
db_index=True)
verb = models.CharField(max_length=255)
target_ct = models.ForeignKey(ContentType,
blank=True,
null=True,
related_name='target_obj')
target_id = models.PositiveIntegerField(null=True,
blank=True,
db_index=True)
target = GenericForeignKey('target_ct', 'target_id')
created = models.DateTimeField(auto_now_add=True,
db_index=True)
class Meta:
ordering = ('-created',)
答案 0 :(得分:1)
您可以使用chain
组合查询集
from itertools import chain
cookie_ids = Cookie.objects.filter(board__pk=self.kwargs['pk']).values_list('id',flat=True)
sugar_ids = Sugar.objects.filter(board__pk=self.kwargs['pk']).values_list('id',Ôflat=True)
ids_list = chain(cookie_ids, sugar_ids)
context['total_actions'] = Action.objects.filter(target_id__in=ids_list)
答案 1 :(得分:0)
我想这就是你想要的
cookie_ids=Cookie.objects.filter(board__pk=self.kwargs['pk']).values_list('id',flat=True)
sugar_ids=Sugar.objects.filter(board__pk=self.kwargs['pk']).values_list('id',Ôflat=True)
ids_list = list(cookie_ids) + list(sugar_ids)
context['total_actions'] = Action.objects.filter(target_id__in=ids_list)
答案 2 :(得分:0)
使用union
cookie_ids = Cookie.objects.filter(board__pk=self.kwargs['pk']).values_list('id',
flat=True)
sugar_ids = Sugar.objects.filter(board__pk=self.kwargs['pk']).values_list('id',
flat=True)
target_ids = cookie_ids.union(sugar_ids)
我的引用:
union
https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet