Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

python - Django: Get an object form the DB, or 'None' if nothing matches

Is there any Django function which will let me get an object form the database, or None if nothing matches?

Right now I'm using something like:

foo = Foo.objects.filter(bar=baz)
foo = len(foo) > 0 and foo.get() or None

But that's not very clear, and it's messy to have everywhere.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two ways to do this;

try:
    foo = Foo.objects.get(bar=baz)
except model.DoesNotExist:
    foo = None

Or you can use a wrapper:

def get_or_none(model, *args, **kwargs):
    try:
        return model.objects.get(*args, **kwargs)
    except model.DoesNotExist:
        return None

Call it like this

foo = get_or_none(Foo, baz=bar)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...