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.
Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With