Django finding which field matched in a multiple OR query
- by Greg Hinch
I've got a couple models which are set up something like this:
class Bar(models.Model):
baz = models.CharField()
class Foo(models.Model):
bar1 = models.ForeignKey(Bar)
bar2 = models.ForeignKey(Bar)
bar3 = models.ForeignKey(Bar)
And elsewhere in the code, I end up with an instance of Bar, and need to find the Foo it is attached to in some capacity. Right now I came up with doing a multiple OR query using Q, something like this:
foo_inst = Foo.objects.get(Q(bar1=bar_inst) | Q(bar2=bar_inst) | Q(bar3=bar_inst))
What I need to figure out is, which of the 3 cases actually hit, at least the name of the member (bar1, bar2, or bar3). Is there a good way to do this? Is there a better way to structure the query to glean that information?