Django finding which field matched in a multiple OR query

Posted by Greg Hinch on Stack Overflow See other posts from Stack Overflow or by Greg Hinch
Published on 2012-09-17T07:42:49Z Indexed on 2012/09/17 9:37 UTC
Read the original article Hit count: 226

Filed under:
|
|
|
|

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?

© Stack Overflow or respective owner

Related posts about python

Related posts about django