DRY and static attribute for multiple classes.
Peter Otten
__peter__ at web.de
Thu Feb 3 04:24:46 EST 2011
Marc Aymerich wrote:
> On Feb 2, 12:11 am, Peter Otten <__pete... at web.de> wrote:
>> Marc Aymerich wrote:
> Hi!,
> Unfortunately per_class attribute losses the "independence" when I try
> to mix it with django models.Model .
>
> from django.db import models
> class Plugin(models.base.ModelBase):
> class __metaclass__(type):
> def __init__(self, *args):
> type.__init__(self, *args)
> self.per_class = []
>
> class BaseService(models.Model):
> class Meta:
> abstract = True
>
> __metaclass__ = Plugin
>
> class VirtualHost(BaseService):
> name = models.CharField(max_length=10)
>
> class SystemUser(BaseService):
> name = models.CharField(max_length=10)
>
>
>>>> VirtualHost.per_class is SystemUser.per_class
> True
>
> What am I doing wrong?
I'm surprised that you are seeing the per_class-attribute at all as you are
defining it in the metaclass of the metaclass, as far as I can tell.
I think the following should work:
from django.db import models
class Plugin(models.base.ModelBase):
def __init__(self, *args):
super(Plugin, self).__init__(*args)
self.per_class = []
class BaseService(models.Model):
class Meta:
abstract = True
__metaclass__ = Plugin
class VirtualHost(BaseService):
name = models.CharField(max_length=10)
class SystemUser(BaseService):
name = models.CharField(max_length=10)
assert VirtualHost.per_class is not SystemUser.per_class
But I have never worked with Django, and the approach based on dictionary
lookup is less likely to interfere with the dark corners of the framework.
Peter
More information about the Python-list
mailing list