问题描述
基本上,我需要一种优雅的方法来执行以下操作:-
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)
是,我需要结束使用Model2的QuerySet以便以后使用(特别是传递给Django表单)。
Yes, I need to end up with a QuerySet of Model2 for later use (specifically to pass to a Django form).
在上面的第一个代码块中,即使我使用 filter
而不是 get
我显然将拥有Model1的QuerySet。在我的情况下,不一定总是可以进行反向查找。
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.
推荐答案
如果您只是想创建一个查询集,通过一些在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.
wanted_items = set()
for item in model1.objects.all():
if check_want_item(item):
wanted_items.add(item.pk)
return model1.objects.filter(pk__in = wanted_items)
您显然必须使其适应您的情况,但这至少应该为您提供一个起点。
You'll obviously have to adapt this to your situation but it should at least give you a starting point.
这篇关于手动创建Django QuerySet或手动将对象添加到QuerySet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!