Reputation: 16506
I have a class that has a number of fields, two of which are many-to-many fields:
class someClass(models.Model):
field1 = ...
field2 = ...
field3 = ...
field4 = models.ManytoManyField(...)
field5 = models.ManytoManyField(...)
I was originally hoping to use someClass.objects.get(...)
later on:
someClass.objects.get(field1=..., field2=..., ...)
I would also like to limit the someClass
es that get returned by field4 and field5 as well. I assume that I cannot do this in a .get()
call because these represent many-to-many relationships that can take many forms.
At the time that I would have been looking to find a unique someClass
, I would have access to several variables that correspond to objects represented in field1-field3, as well as two short lists of objects that correspond to the objects represented in field4 and in field5. These together should describe a unique instance.
Accepting that I may have to do this in a series of .filter()
s, what is the best way for me to obtain the single someClass
object that my data (again, one variable apiece for field1-field3 and two lists for field4 and field5) describes?
Upvotes: 2
Views: 119
Reputation: 118458
I think the answer is as obvious as you expect...
You definitely can't use get
here because of the m2m
s - you have to chain the filters to exclude results that contain inexact m2m matches.
query = someClass.objects.filter(field1=field1, field2=field2, field3=field3)
for item in list1:
query = query.filter(foo=item)
for item in list2:
query = query.filter(bar=item)
# substitute with fancy python as you wish.
Upvotes: 1