Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Models: add safe_get_or_create utility

This provides the convenience of .get_or_create but uses full model validation
and uses setattr() so custom setter logic is consistently applied
  • Loading branch information...
commit ef858e8318baa31d50fab8cce30a6fc6a847e51c 1 parent 51c6f36
@acdha authored
Showing with 34 additions and 0 deletions.
  1. +34 −0 sugar/models.py
View
34 sugar/models.py
@@ -0,0 +1,34 @@
+# encoding: utf-8
+from __future__ import absolute_import
+
+
+def safe_get_or_create(klass, **kwargs):
+ """
+ Similar to :meth:`~django.db.models.query.QuerySet.get_or_create` but uses
+ the methodical get/save including a full_clean() call to avoid problems with
+ models which have validation requirements which are not strictly enforced by
+ the underlying database
+
+ For example, with a django-model-translation we always want to go through
+ the setattr route rather than inserting into the database so translated
+ fields will be mapped according to the active language. This avoids normally
+ impossible situations such as creating a record where `title` is defined but
+ `title_en` is not.
+ """
+
+ defaults = kwargs.pop("defaults", {})
+
+ try:
+ obj = klass.objects.get(**kwargs)
+ return (obj, False)
+ except klass.DoesNotExist:
+ obj = klass()
+
+ for k, v in kwargs.items() + defaults.items():
+ setattr(obj, k, v)
+
+ obj.full_clean()
+ obj.save()
+ return (obj, True)
+
+
Please sign in to comment.
Something went wrong with that request. Please try again.