Check if a OneToOne relation exists in Django

前端 未结 3 1275
無奈伤痛
無奈伤痛 2021-01-01 14:27

Now I\'m using django 1.6

I have two models relates with a OneToOneField.

class A(models.Model):
    pass

class B(models.Model):
    re         


        
3条回答
  •  鱼传尺愫
    2021-01-01 14:54

    hasattr works fine with Django1.11 ! You may use getattr for shorter version:

    getattr(self, 'field', default)
    

    In your case

    b = getattr(a, 'ref_b', None)
    

    https://docs.python.org/3.6/library/functions.html#getattr

提交回复
热议问题