我有几个模型是这样设置的:
class Bar(models.Model):
baz = models.CharField()
class Foo(models.Model):
bar1 = models.ForeignKey(Bar)
bar2 = models.ForeignKey(Bar)
bar3 = models.ForeignKey(Bar)
在代码的其他地方,我以 Bar 的实例结束,并且需要找到它以某种身份附加到的 Foo。现在我想到了使用 Q 进行多重 OR 查询,如下所示:
foo_inst = Foo.objects.get(Q(bar1=bar_inst) | Q(bar2=bar_inst) | Q(bar3=bar_inst))
我需要弄清楚的是,这 3 个案例中的哪一个实际命中,至少是成员的名称(bar1、bar2 或 bar3)。有没有好的方法来做到这一点?是否有更好的方法来构造查询以收集该信息?
请您参考如下方法:
try:
Foo.objects.get(bar1=bar_inst)
print 'bar1'
except Foo.DoesNotExist:
try:
Foo.objects.get(bar2=bar_inst)
print 'bar2'
except Foo.DoesNotExist:
try:
Foo.objects.get(bar3=bar_inst)
print 'bar3'
except Foo.DoesNotExist:
print 'nothing found'
还可以考虑添加 related_name到模型的所有栏字段。
