I am trying to write a singleton model which can be subclassed.
from django.db import models
class Singleton(models.Model):
name = models.TextField()
def save(self):
if self.__class__.objects.all().count():
#There exists another object in the DB
obj = self.__class__.objects.all()[0]
for field in self._meta.fields:
if not field.name == self._meta.auto_field.name:
setattr(obj, field.name, getattr(self,
field.name))
super(Singleton, obj).save()
else:
super(Singleton, self).save()
class SubSingleton(Singleton):
tag = models.TextField()
I want an API like this,
In [1]: from testf.models import SubSingleton
In [2]: SubSingleton.objects.all().delete()
In [3]: x=SubSingleton(name='a', tag='b')
In [4]: x.save()
In [5]: SubSingleton.objects.count()
Out[5]: 1
In [6]: y=SubSingleton(name='a', tag='b')
In [7]: y.save()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call
last)
/home/shabda/django_design_pats/<ipython console> in <module>()
/home/shabda/django_design_pats/testf/models.pyc in save(self)
9 obj = self.__class__.objects.all()[0]
10 for field in self._meta.fields:
---> 11 if not field.name ==
self._meta.auto_field.name:
12 setattr(obj, field.name, getattr(self,
field.name))
13 super(Singleton, obj).save()
AttributeError: 'NoneType' object has no attribute 'name'
In [8]: SubSingleton.objects.count()
Out[8]: 1
So SubSingleton._meta.auto_field is none, while I expect it to be a
AutoField with name ='id'.
What am I missing?
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---