django - 是否可以在 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',)
解决方案
您可以使用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)
推荐阅读
- git - 克隆时Git将中文文本添加到xml文件
- javascript - Splash 阻止 JS 执行
- php - 使用 PHP 或 MySQL 在数据库中获得最快的 0-60
- sql - T-SQL:从基于字符串的 SELECT 语句中排除列
- angular - Angular - 去抖动清晰度 vm-ware datagrid clrDgRefresh
- javascript - Сurve 线作为没有地图的两点之间的方向
- javascript - 如何从网页将javascript值加载到python中?
- c - 我们是否必须在 switch 语句之后添加一些东西
- python - 我将 python 3.6.4 更新到 3.7.2_2 并且我所有导入的模块都停止工作
- nginx - 如何为 kubernetes nginx-ingress 启用 vts 仪表板?