69๐
โ
How about this:
obj = Model.objects.filter(id=1).first()
now if no object with id=1 exists obj would be None
Ref: https://docs.djangoproject.com/en/3.2/ref/models/querysets/#django.db.models.query.QuerySet.first
๐คGaurav
3๐
If you are using it in a web request, and you want to return a 404 if the object does not exist you can use
from django.shortcuts import get_object_or_404
get_object_or_404(Mode, pk=1)
๐คJoseP
- [Django]-Django.contrib.auth.logout in Django
- [Django]-Django: How can I protect against concurrent modification of database entries
- [Django]-How do you Serialize the User model in Django Rest Framework
- [Django]-Do properties work on Django model fields?
- [Django]-How do I use a dictionary to update fields in Django models?
- [Django]-Add rich text format functionality to django TextField
1๐
i think better to reuse Django functionality as much as possible, and django has 99% similar func get_object_or_404
which just raises Http404
from django.shortcuts import get_object_or_404
def get_or_none(model_or_qs, **kwargs):
try:
return get_object_or_404(model_or_qs, **kwargs)
except Http404:
return None
Some tests cases that shows that code can be used for Model, Queryset, RelatedManager
[in tests one User can Have multiple Contacts]
@test_for(get_or_none)
def test_get_or_none_for_model(self):
self.assertEqual(self.user, get_or_none(User, pk=self.user.pk))
self.assertEqual(None, get_or_none(User, pk=777))
@test_for(get_or_none)
def test_get_or_none_for_queryset_and_manager(self):
contact = ContactFactory(user=self.user)
self.assertEqual(self.user, get_or_none(User.objects, pk=self.user.pk))
self.assertEqual(self.user, get_or_none(User.objects.all(), pk=self.user.pk))
self.assertEqual(contact, get_or_none(Contact.objects.filter(user=self.user)))
self.assertEqual(contact, get_or_none(self.user.contacts))
self.assertEqual(None, get_or_none(User.objects.all(), pk=777))
self.assertEqual(None, get_or_none(self.user.contacts, pk=777))
๐คpymen
- [Django]-Django 1.5 โ How to use variables inside static tag
- [Django]-Django Passing data between views
- [Django]-Django templates โ split string to array
0๐
get_object_or_404
in your model do . . .
@models.permalink
def get_absolute_url(self):
return "/blog/%s/" self.slug
๐คeusid
- [Django]-"_set" in a queryset object in Django
- [Django]-Django Management Command Argument
- [Django]-TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
Source:stackexchange.com