检查Django中是否存在OneToOne关系 [英] Check if a OneToOne relation exists in Django
问题描述
现在我正在使用Django 1.6
Now I'm using django 1.6
我有两个与OneToOneField
相关的模型.
I have two models relates with a OneToOneField
.
class A(models.Model):
pass
class B(models.Model):
ref_a = models.OneToOneField(related_name='ref_b', null=True)
首先请参阅指出问题的代码:
First see my code that points out the problem:
a1 = A.objects.create()
a2 = A.objects.create()
b1 = B.objects.create()
b2 = B.objects.create(ref_a=a2)
# then I call:
print(a1.ref_b) # DoesNotExist Exception raised
print(a2.ref_b) # returns b2
print(b1.ref_a) # returns None
print(b2.ref_a) # returns a2
现在的问题是,如果我要检查A
对象,请判断它是否存在引用它的B
对象.我该怎么办?
Now the problem is, if I want to check a A
object, to judge whether it exists a B
objects referencing it. How can I do?
我尝试过的有效方法只是尝试捕获异常,但是还有其他更漂亮的方法吗?
The valid way I tried is only to try and catch an exception, but is there any other prettier way?
我的努力:
1-以下代码有效,但是太难看了!
1 - The below code works, but is too ugly!
b = None
try:
b = a.ref_b
except:
pass
2-我还尝试检查a中的属性,但不起作用:
2 - I also tried to check the attributes in a, but not working:
b = a.ref_b if hasattr(a, 'ref_b') else None
朋友,您遇到同样的问题吗?请给我指出一种方式,谢谢!
Do you meet the same problem, friends? Please point me a way, thank you!
推荐答案
因此,您至少有两种检查方法.
首先是创建try/catch块以获取属性,其次是使用hasattr
.
So you have a least two ways of checking that.
First is to create try/catch block to get attribute, second is to use hasattr
.
class A(models.Model):
def get_B(self):
try:
return self.b
except:
return None
class B(models.Model):
ref_a = models.OneToOneField(related_name='ref_b', null=True)
请尝试避免使用裸露的except:
子句.它可以隐藏一些问题.
Please try to avoid bare except:
clauses. It can hide some problems.
第二种方法是:
class A(models.Model):
def get_B(self):
if(hasattr(self, 'b')):
return self.b
return None
class B(models.Model):
ref_a = models.OneToOneField(related_name='ref_b', null=True)
在两种情况下,您都可以毫无例外地使用它:
In both cases you can use it without any exceptions:
a1 = A.objects.create()
a2 = A.objects.create()
b1 = B.objects.create()
b2 = B.objects.create(ref_a=a2)
# then I call:
print(a1.get_b) # No exception raised
print(a2.get_b) # returns b2
print(b1.a) # returns None
print(b2.a) # returns a2
There is no other way, as throwing the exception is default behaviour from Django One to One relationships.
这是官方文档中处理它的示例.
And this is the example of handling it from official documentation.
>>> from django.core.exceptions import ObjectDoesNotExist
>>> try:
>>> p2.restaurant
>>> except ObjectDoesNotExist:
>>> print("There is no restaurant here.")
There is no restaurant here.
这篇关于检查Django中是否存在OneToOne关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!