My model definition:
class Thing1(models.Model):
thing2s = models.ManyToManyField(Thing2, blank=True)
I have an instance of Thing2, called myThing2.
I want to do something like this:
Thing1.objects.get(thing2s__contains = myThing2)
That doesn’t work as functional code, but hopefully you get my point. (I’m trying to find a Thing1 that has myThing2 in it’s thing2s field.) How might I do that?
Thanks for the help!
Personally, I would add a ‘related_name’ to your many to many definition.
Something like
Then, from your Thing2, you can access the ‘thing1s’ that it relates to by….
But,I have to ask, as was stated above, if thing2 can only be related to a single thing1, then you should be using a ForeignKey(in Thing2, instead of Thing1) instead of ManyToMany. But, the above solution still works.
So, your classes would be….
So, from a thing2, you could get at its single thing1 by simply….
and from a thing1, you could get a list of all the thing2s that reference it via….