Unknown
Unknown

Reputation: 23

Django model object access in views

I have a view in django which get a value through post request and i want to get a model object using that value as an attribute. View is as:

def accessObject(request):
     if request.method =="POST":
          value = request.POST.get('value')
          object = RandomModel.objects.get(value=value)
     return render(request,template,{'object':object})

I want to know if this is the correct way of doing things in production, because if value is an integer type then the view will throw an error even if object exists. Should I use type conversion every time I write this type of view in django?

Upvotes: 0

Views: 47

Answers (1)

schillingt
schillingt

Reputation: 13731

Below is how I typically handle these things. Your question is lacking some context, so I made a few assumptions.

from django.http import Http404
from django.shortcuts import get_object_or_404

def accessObject(request):
     if request.method =="POST":
          try:
              # Do any necessary casting here. You mentioned int conversion so I used that.
              value = int(request.POST.get('value'))
          except TypeError:
              # Or return whichever http status you think is more appropriate for you.
              raise Http404
          object = get_object_or_404(RandomModel, value=value)
     return render(request,template,{'object':object})

Upvotes: 2

Related Questions