1. Curtis Maloney
  2. gnocchi-tools

Commits

funkybob  committed ea7f660

Added AutoOneToOneField

  • Participants
  • Parent commits 14a15f9
  • Branches default

Comments (0)

Files changed (2)

File gnocchi/tools/fields.py

View file
  • Ignore whitespace
+from django.db.models.fields import related
+from django.db import router
+
+class AutoSingleRelatedObjectDescriptor(related.SingleRelatedObjectDescriptor):
+    def __get__(self, instance, instance_type=None):
+        if instance is None:
+            return self
+        try:
+            return getattr(instance, self.cache_name)
+        except AttributeError:
+            rel = self.related
+            params = {'%s' % rel.field.name: instance}
+            db = router.db_for_read(rel.model, instance=instance)
+            rel_obj = rel.model._base_manager.using(db).get_or_create(**params)[0]
+            setattr(instance, self.cache_name, rel_obj)
+            return rel_obj
+
+
+class AutoOneToOneField(related.OneToOneField):
+    '''A OneToOne field that will create an instance if the target looks us up.'''
+    def contribute_to_related_class(self, cls, related):
+        setattr(cls, related.get_accessor_name(),
+            AutoSingleRelatedObjectDescriptor(related)
+        )

File setup.py

View file
  • Ignore whitespace
 from setuptools import setup, find_packages
 
 setup( name='gnocchi-tools',
-    version = '1.1.2',
+    version = '1.1.3',
     description = 'Common tools used by Gnocchi apps',
     author = 'Curtis Maloney',
     author_email = 'curtis@tinbrain.net',