manually create a Django QuerySet or rather manually add objects to a QuerySet

天涯浪子 提交于 2020-05-24 17:27:26

问题


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.


回答1:


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.




回答2:


To manually add objects to a QuerySet, try _result_cache:

objs = ObjModel.objects.filter(...)
len(objs) #or anything that will evaluate and hit the db
objs._result_cache.append(yourObj)

PS: I did not understand (or tried to) chefsmart's question but I believe this answers to the question in title.




回答3:


You can't manually add objects to a QuerySet. But why don't you put them in a list ?

obj1 = Model1.objects.select_related('model2').get(attribute1=value1)
obj2 = Model1.objects.select_related('model2').get(attribute2=value2)
model2 = list(obj1, obj2)


来源:https://stackoverflow.com/questions/3397437/manually-create-a-django-queryset-or-rather-manually-add-objects-to-a-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!