質問

I have an object that may or may not exist. Due to this fact I have wrapped the statement in a try / except block.

try:
        generic_type = ContentType.objects.get_for_model(myentity)
        my_object = MyObject.objects.filter(content_type__pk=generic_type.id, object_id=myentity.id)[0]
except:

The reason I ask is because I have nothing to put in the Except condition in this situation, but django/python requires it.

Is this the proper way to handle this situation? If it is, what should I put after the Except?

役に立ちましたか?

解決

You can use the pass statement anywhere a statement is required when you want to do nothing, although you should specify the actual exception to catch.

except WhateverExceptionGetsRaised:
    pass

他のヒント

If you are retrieving an object based on "PK" then it is only going to return one object. There isn't a need for multiple filters. Instead of:

my_object = MyObject.objects.filter(content_type__pk=generic_type.id, object_id=myentity.id)[0]

You can use:

my_object = MyObject.objects.get(content_type__pk=generic_type.id, '')

You would use this if you want it to return nothing hence the double single quotes if it fails to get the first object specified. This may be a more concise answer than an try/except pattern. Also, using:

filter()[0] vs. get()

will both return one object, but filter()[0] returns a QuerySet object type, where as get() returns the object only, so this is another thing to consider.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top