首页 > 解决方案 > 是否可以在 Django 中组合多个 values_list() ?

问题描述

正如标题所示,我有多组查询,每组都返回一个值列表。然后我使用值列表来过滤另一个查询集。目前,我一次只能执行第二步一个查询集。是否可以将我的初始值列表组合成一个超长列表?我正在尝试创建类似功能的活动/新闻提要。

视图.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',)

标签: djangodjango-modelsdjango-queryset

解决方案


您可以使用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)

推荐阅读