简体   繁体   English

Python Django检查属性是否存在或是否已设置

[英]Python Django check if an attribute exists or has been set

I have a User object and a UserInfo object which have a one to one relationship. 我有一个User对象和一个UserInfo对象,它们具有一对一的关系。 I am just adding the UserInfo object so some users already have User objects but not UserInfo objects. 我只是添加了UserInfo对象,因此一些用户已经拥有User对象而不是UserInfo对象。 I want to check to see if the User object has a UserInfo object associated with it yet and if not redirect them to a page where I can get some info. 我想检查User对象是否有与之关联的UserInfo对象,如果没有将它们重定向到我可以获取一些信息的页面。 I am still new to python and have tried doing an if request.user.user_info: which throws an exception when it doesn't exist so I ended up doing this: 我仍然是python的新手,并尝试过if request.user.user_info:当它不存在时抛出异常,所以我最终这样做:

 user = request.user
    try:
        user.user_info.university
    except:
        print 'redirect to info page'

which works fine, but I feel like exceptions should be for exceptions and not for if statement substitutes. 哪个工作正常,但我觉得异常应该是异常,而不是if语句替换。 Is there a better way to do this? 有一个更好的方法吗?

I'd say that handling this with exceptions is the pythonic approach. 我会说处理这个例外的是pythonic方法。 You can do something like this: 你可以这样做:

try:
    # do your thing when user.user_info exists
except AttributeError: # Be explicit with catching exceptions.
    # Redirect.

There's a programming concept called it's easier to ask for forgiveness than permission (EAFP) which is used extensively in Python. 有一种编程概念称为it's easier to ask for forgiveness than permission (EAFP)而不是在Python中广泛使用的it's easier to ask for forgiveness than permission (EAFP) We assume that attributes, keys and so forth exist for a given object and catch exceptions when they do not. 我们假设对于给定对象存在属性,键等,并且当它们不存在时捕获异常。

Here are some references and SO questions about EAFP. 以下是关于EAFP的一些参考和SO问题。

Python glossary Python词汇表
What is the EAFP principle in Python 什么是Python中的EAFP原则
EAFP and what is really exceptional EAFP和什么是非常特殊的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM