如何将模型实例添加到Django查询集? [英] How to add an model instance to a django queryset?
本文介绍了如何将模型实例添加到Django查询集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
django查询集的行为似乎类似于python列表。
It seems like a django queryset behaves somehow like a python list.
但是据我所知,它不支持列表的.append()方法。
But it doesn't support list's .append() method as I know.
我想做的事情是:
from my_django_app.models import MyModel
queryset = MyModel.objects.none()
queryset.append(MyModel.objects.first()) ## no list's .append() method!
是否可以将模型实例添加到现有查询集中?
Is there any way to add an model instance to an existing queryset?
推荐答案
您还可以使用 |
运算符创建联合:
You can also use the |
operator to create a union:
queryset = MyModel.objects.none()
instance = MyModel.objects.first()
queryset |= MyModel.objects.filter(pk=instance.pk)
但是请注意,这将根据数量生成不同的查询这样添加的项目数量,使已编译查询的缓存效率低下。
But be warned that this will generate different queries depending on the number of items you append this way, making caching of compiled queries inefficient.
这篇关于如何将模型实例添加到Django查询集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文