手动创建 Django QuerySet 或者手动将对象添加到 QuerySet
基本上我需要一种优雅的方式来执行以下操作:-
obj1 = Model1.objects.select_related('model2').get(attribute1=value1)
obj2 = Model1.objects.select_related('model2').get(attribute2=value2)
model2_qs = QuerySet(model=Model2, qs_items=[obj1.model2,obj2.model2])
我可能没有正确思考,但是做类似以下的事情对我来说似乎无限愚蠢。:-
obj1 = Model1.objects.select_related('model2').get(attribute1=value1)
model2_qs = Model2.objects.filter(pk=obj1.model2.pk)
是的,我需要最终得到 Model2 的 QuerySet 供以后使用(特别是传递到 Django 表单)。
在上面的第一个代码块中,即使我使用 filter
而不是 get
,我显然也会有一个 Model1 的 QuerySet。在我的情况下,反向查找可能并不总是可行。
Basically I need a graceful way to do the following:-
obj1 = Model1.objects.select_related('model2').get(attribute1=value1)
obj2 = Model1.objects.select_related('model2').get(attribute2=value2)
model2_qs = QuerySet(model=Model2, qs_items=[obj1.model2,obj2.model2])
I may not be thinking right, but doing something like the following seems infinitely stupid to me.: -
obj1 = Model1.objects.select_related('model2').get(attribute1=value1)
model2_qs = Model2.objects.filter(pk=obj1.model2.pk)
Yes, I need to end up with a QuerySet of Model2 for later use (specifically to pass to a Django form).
In the first code block above,even if I use filter
instead of get
I will obviously have a QuerySet of Model1. Reverse lookups may not always be possible in my case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您只是想创建一个项目的查询集,您可以通过一些无法在 SQL 中表示的复杂过程来选择这些项目,那么您始终可以使用 __in 运算符。
显然,您必须根据您的情况进行调整,但它至少应该为您提供一个起点。
If you're simply looking to create a queryset of items that you choose through some complicated process not representable in SQL you could always use the
__in
operator.You'll obviously have to adapt this to your situation but it should at least give you a starting point.
要手动将对象添加到 QuerySet,请尝试
_result_cache
:PS:我不理解(或试图)chefsmart 的问题,但我相信这回答了标题中的问题。
To manually add objects to a QuerySet, try
_result_cache
:PS: I did not understand (or tried to) chefsmart's question but I believe this answers to the question in title.
您无法手动将对象添加到查询集。但你为什么不把它们列在一个列表中呢?
You can't manually add objects to a QuerySet. But why don't you put them in a list ?