python - In Django how to avoid boilerplate code for getting model instance by pk in a view -


here example code:

def someview(request):     try:         instance = somemodel.objects.get(id=request.get.get('id'))     except somemodel.doesnotexist:         instance = none     except valueerror:         # error may occur if user manually enter invalid (non-integer)         # id value (intentionally or not) in browser address bar, e.g.         # http://example.com/?id=2_foo instead of http://example.com/?id=2         # raises valueerror: invalid literal int() base 10: '2_'         instance = none     ... 

is there best practice model instance pk without writing boilerplate code on , over? should use predefined shortcut in django or roll own?

i sure should use django's detailview or singleobjectmixin curiously enough doesn't handle valueerror exception example https://github.com/django/django/blob/master/django/views/generic/detail.py#l50
implied have specify correct integer regexp pk kwarg in urlconf? ok, likely. if pk request querystring?

upd have special logic instance either it's none or not.

you can use django's built in shorcut get_object_or_404() it's designed specifically. function raise http404 exception in case object doesn't exist. if want none instead of raising exception, can create helper function accomplish easily:

def get_object_or_none(klass, *args, **kwargs):     try:         return get_object_or_404(klass, *args, **kwargs)     except http404:         return none 

hope helps!


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -