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
1.4k views
in Technique[技术] by (71.8m points)

django - How to handle "matching query does not exist" when getting an object

When I want to select objects with a get() function like

personalProfile = World.objects.get(ID=personID)

If get function doesn't return find a value, a "matching query does not exist." error occurs.

If I don't need this error, I'll use try and except function

try:
   personalProfile = World.objects.get(ID=personID)
except:
   pass

But I think this is not the best way since I use

except:
      pass

Please recommend some idea or code sample to fight with this issue

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

That depends on what you want to do if it doesn't exist..

Theres get_object_or_404:

Calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception.

get_object_or_404(World, ID=personID)

Which is very close to the try except code you currently do.

Otherwise theres get_or_create:

personalProfile, created = World.objects.get_or_create(ID=personID)

Although, If you choose to continue with your current approach, at least make sure the except is localised to the correct error and then do something with that as necessary

try:
   personalProfile = World.objects.get(ID=personID)
except MyModel.DoesNotExist:
    raise Http404("No MyModel matches the given query.")

The above try/except handle is similar to what is found in the docs for get_object_or_404...


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

1.4m articles

1.4m replys

5 comments

57.0k users

...