94👍
In Django 1.6 you can use the first()
Queryset method. It returns the first object matched by the queryset, or None if there is no matching object.
Usage:
p = Article.objects.order_by('title', 'pub_date').first()
149👍
There are two ways to do this;
try:
foo = Foo.objects.get(bar=baz)
except model.DoesNotExist:
foo = None
Or you can use a wrapper:
def get_or_none(model, *args, **kwargs):
try:
return model.objects.get(*args, **kwargs)
except model.DoesNotExist:
return None
Call it like this
foo = get_or_none(Foo, baz=bar)
- [Django]-Factory-boy create a list of SubFactory for a Factory
- [Django]-Django Forms: if not valid, show form with error message
- [Django]-Changing a project name in django
84👍
To add some sample code to sorki’s answer (I’d add this as a comment, but this is my first post, and I don’t have enough reputation to leave comments), I implemented a get_or_none custom manager like so:
from django.db import models
class GetOrNoneManager(models.Manager):
"""Adds get_or_none method to objects
"""
def get_or_none(self, **kwargs):
try:
return self.get(**kwargs)
except self.model.DoesNotExist:
return None
class Person(models.Model):
name = models.CharField(max_length=255)
objects = GetOrNoneManager()
And now I can do this:
bob_or_none = Person.objects.get_or_none(name='Bob')
- [Django]-Django dynamic forms – on-the-fly field population?
- [Django]-Django can' t load Module 'debug_toolbar': No module named 'debug_toolbar'
- [Django]-Django development server reload takes too long
14👍
You can also try to use django annoying (it has another useful functions!)
install it with:
pip install django-annoying
from annoying.functions import get_object_or_None
get_object_or_None(Foo, bar=baz)
- [Django]-Uninstall Django completely
- [Django]-What is the easiest way to clear a database from the CLI with manage.py in Django?
- [Django]-Can't compare naive and aware datetime.now() <= challenge.datetime_end
10👍
Give Foo its custom manager. It’s pretty easy – just put your code into function in custom manager, set custom manager in your model and call it with Foo.objects.your_new_func(...)
.
If you need generic function (to use it on any model not just that with custom manager) write your own and place it somewhere on your python path and import, not messy any more.
- [Django]-Adding to the "constructor" of a django model
- [Django]-What's the purpose of Django setting ‘SECRET_KEY’?
- [Django]-How to rename items in values() in Django?
4👍
Whether doing it via a manager or generic function, you may also want to catch ‘MultipleObjectsReturned’ in the TRY statement, as the get() function will raise this if your kwargs retrieve more than one object.
Building on the generic function:
def get_unique_or_none(model, *args, **kwargs):
try:
return model.objects.get(*args, **kwargs)
except (model.DoesNotExist, model.MultipleObjectsReturned), err:
return None
and in the manager:
class GetUniqueOrNoneManager(models.Manager):
"""Adds get_unique_or_none method to objects
"""
def get_unique_or_none(self, *args, **kwargs):
try:
return self.get(*args, **kwargs)
except (self.model.DoesNotExist, self.model.MultipleObjectsReturned), err:
return None
- [Django]-Testing email sending in Django
- [Django]-Django dynamic forms – on-the-fly field population?
- [Django]-Why doesn't django's model.save() call full_clean()?
0👍
Here’s a variation on the helper function that allows you to optionally pass in a QuerySet
instance, in case you want to get the unique object (if present) from a queryset other than the model’s all
objects queryset (e.g. from a subset of child items belonging to a parent instance):
def get_unique_or_none(model, queryset=None, *args, **kwargs):
"""
Performs the query on the specified `queryset`
(defaulting to the `all` queryset of the `model`'s default manager)
and returns the unique object matching the given
keyword arguments. Returns `None` if no match is found.
Throws a `model.MultipleObjectsReturned` exception
if more than one match is found.
"""
if queryset is None:
queryset = model.objects.all()
try:
return queryset.get(*args, **kwargs)
except model.DoesNotExist:
return None
This can be used in two ways, e.g.:
obj = get_unique_or_none(Model, *args, **kwargs)
as previosuly discussedobj = get_unique_or_none(Model, parent.children, *args, **kwargs)
- [Django]-Django 1.5 custom User model error. "Manager isn't available; User has been swapped"
- [Django]-How to get the ID of a just created record in Django?
- [Django]-Django switching, for a block of code, switch the language so translations are done in one language
-3👍
I think that in most cases you can just use:
foo, created = Foo.objects.get_or_create(bar=baz)
Only if it is not critical that a new entry will be added in Foo table ( other columns will have the None/default values )
- [Django]-Get object by field other than primary key
- [Django]-Django admin make a field read-only when modifying obj but required when adding new obj
- [Django]-Django get a QuerySet from array of id's in specific order