1

I'm trying to generate models that record some fields of other models, using metaclass.

My plan is to copy recording_fields of recording_model(which is a model to be recorded), and register them on the subclasses of RecordModel via contribute_to_class(cls,name) method of django's Field.

In this way, it will be able to automatically create records whenever one of recording_model's recording_fields has been changed, using signals.

The problem is that I have to create exactly same Field instances with recording_model's, including database constraints and requirements (e.g. max_length argument).

So the situation is

from django.models import Model
from django.models.base import ModelBase


class TimeStampedModel(Model):

    ...

    class Meta:
        abstract = True
        ...


class RecordModelMetaClass(ModelBase):
    def __init__(cls, name, bases, attrs):

        ...

        # Register 'recording_fields' of 'recording_model'
        # to subclasses of RecordModel (not reference, deep copy)
        # using `contribute_to_class`.

        ...


class RecordModel(TimeStampedModel):
    __metaclass__ = RecordModelMetaClass

    recording_model = NotImplemented
    recording_fields = NotImplemented

    class Meta(TimeStampedModel.Meta):
        abstract = True

where RecordModel will be the abstract base class of all records.

I know I can use Model._meta.get_field() method to retrieve an Field instance of a model, but what I need is copy of an instance, not reference.

Is there any way to make an deep copy of an Field instance in django?

June
  • 2,107
  • 4
  • 22
  • 33
  • 1
    Have you seen the answer to this question? http://stackoverflow.com/questions/12222003/copying-a-django-field-description-from-an-existing-model-to-a-new-one – Bob Barcklay May 12 '15 at 15:40

0 Answers0