Check if OneToOneField is None in Django

后端 未结 8 1788
走了就别回头了
走了就别回头了 2021-01-30 10:04

I have two models like this:

class Type1Profile(models.Model):
    user = models.OneToOneField(User, unique=True)
    ...


class Type2Profile(models.Model):
            


        
8条回答
  •  野性不改
    2021-01-30 10:41

    How about using try/except blocks?

    def get_profile_or_none(user, profile_cls):
    
        try:
            profile = getattr(user, profile_cls.__name__.lower())
        except profile_cls.DoesNotExist:
            profile = None
    
        return profile
    

    Then, use like this!

    u = request.user
    if get_profile_or_none(u, Type1Profile) is not None:
        # do something
    elif get_profile_or_none(u, Type2Profile) is not None:
        # do something else
    else:
        # d'oh!
    

    I suppose you could use this as a generic function to get any reverse OneToOne instance, given an originating class (here: your profile classes) and a related instance (here: request.user).

提交回复
热议问题