Reputation: 8782
I have 2 models which have foreign keys referencing a third model. Its something like this:
class Foo(models.Model):
...
class Model1(models.Model):
foo = models.ForeignKey(Foo, related_name='m1_related')
class Model2(models.Model):
foo = models.ForeignKey(Foo, related_name='m2_related')
Now, lets say I have an instance of Foo
and a string which is either 'm1'
or 'm2'
. How can I use this string to call the appropriate queryset using the related names?
Something like this:
my_str = 'm1'
foo.my_str+'_related'.objects.all()
Obviously, the above code is just wrong in so many ways, but hopefully that makes it clear. I don't want to use if else conditions for this, as the number of models will be a lot, and all their related names will follow the same pattern.
Thanks.
Upvotes: 0
Views: 39
Reputation: 477607
You can use getattr(..)
to obtain the name of an attribute, like:
my_str = 'm1'
getattr(foo, my_str+'_related').objects.all()
A call to getattr(x, 'y')
is equivalent to x.y
(note that in getattr(..)
the 'y
' is a string. So we can use getattr(..)
obtain the attribute.
Upvotes: 2