I am trying to get a particular object from Django... When I use filter it returns more than one and I need just one and I don't want to my fields unique... Is there a way I can get object by id since id will be the only unique field by default in Django Sqlite
CodePudding user response:
You can use two methods get()
or more better get_object_or_404()
as it calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception.
Implementation of get()
:
SomeModelName.objects.get(id=id)
Implementation of get_object_or_404()
:
from django.shortcuts import get_object_or_404
get_object_or_404(SomeModelName,id=id)
CodePudding user response:
You can choose one of these methods to get the object related to id
you entered:
get_object_or_404()
function:
from django.shortcuts import get_object_or_404
model_object = get_object_or_404(ModelName, id=id)
.get_or_create()
method:
model_object, created = ModelName.objects.get_or_create(id=id)
.filter()
and .first()
methods:
model_object = ModelName.objects.filter(id=id).first()
CodePudding user response:
Yourtablename.object.get(pk=id)
Or use filter