python - Check if a OneToOne relation exists in Django -
now i'm using django 1.6
i have 2 models relates onetoonefield.
class a(models.model):     pass  class b(models.model):     ref_a = models.onetoonefield(related_name='ref_b', null=true) first see code points out problem:
a1 = a.objects.create() a2 = a.objects.create() b1 = b.objects.create() b2 = b.objects.create(ref_a=a2)  # 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 now problem is, if want check a object, judge whether exists b objects referencing it. how can do?
the valid way tried try , catch exception, there other prettier way?
my effort:
1 - below code works, ugly!
b = none try:     b = a.ref_b except:     pass 2 - tried check attributes in a, not working:
b = a.ref_b if hasattr(a, 'ref_b') else none do meet same problem, friends? please point me way, thank you!
so have least 2 ways of checking that. first create try/catch block attribute, second 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) please try avoid bare except: clauses. can hide problems.
the second way is:
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 can use without exceptions:
a1 = a.objects.create() a2 = a.objects.create() b1 = b.objects.create() b2 = b.objects.create(ref_a=a2)  # 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 no other way, throwing exception default behaviour django one 1 relationships.
and example of handling official documentation.
>>> django.core.exceptions import objectdoesnotexist >>> try: >>>     p2.restaurant >>> except objectdoesnotexist: >>>     print("there no restaurant here.") there no restaurant here. 
Comments
Post a Comment