On Feb 4, 2008, at 7:50 AM, Brian Harring wrote:
>
> This is a dirty hack mind you, but a rather effective one- I
> personally use it for when I need to create common structures w/in
> tables and need to able to change the structure definitions in a
> single spot. If you did the following-
>
> def add_common_fields(local_scope):
> local_scope['field1'] = models.IntegerField(blank=True,
> null=True)
> local_scope['field2'] = models.CharField(maxlength=255,
> blank=True, null=True)
> # other common definitions, same thing, updating the passed in
> # dict
>
> you could then just do
>
> class Model_A(models.Model):
> add_common_fields(locals())
> # other fields
>
> class Model_B(models.Model):
> add_common_fields(locals())
> # other fields.
...
> You probably could fold the approach above into a metaclass if desired
> also- would be a bit more pythonic possibly.
Since we've been using a metaclass for doing a similar task, seems
appropriate to paste it now:
class ModelMixinBase(ModelBase):
def __new__(cls, name, bases, attrs):
new_attrs = attrs.copy()
for attr,value in cls.__dict__.iteritems():
if isinstance(value, models.Field):
new_attrs.setdefault(attr,value)
elif attr == 'methods':
for v in value:
if callable(v):
new_attrs.setdefault(v.__name__, v)
elif isinstance(v, str):
new_attrs.setdefault(v, getattr(cls, v))
return super(ModelMixinBase, cls).__new__(cls, name, bases,
new_attrs)
class MixinBaseA(ModelMixinBase):
common_1 = models.IntegerField()
common_2 = models.CharField(max_length=255)
class ResultModel(models.Model):
__metaclass__ = MixinBaseA
specific_1 = models.IntegerField()
The end result should give you as far as we have been able to tell a
perfectly okay Django model instance (we've been using it for months
and haven't seen any weird behavior yet). We know it does a touch
more than what yours does, but it could easily be stripped down to
just be the equivalent of what you've got above.
gav
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django developers" 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-developers?hl=en
-~----------~----~----~----~------~----~------~--~---