Saturday, June 28, 2014

Right way add dynamically fields to model and migrations

Hi all!

Have little problem.

I have Custom Field like abstract RichTextEditor which can parse entered text to html some ways. For performance optimization this fields caches parsed data in separate field of model which creates dynamically.

Take a look into code.

    def contribute_to_class(self, cls, name):
        if self.add_rendered_field and not cls._meta.abstract:
            preview_field = models.TextField(editable=False, blank=True, null='')
            cls.add_to_class(_preview_field_name(name), preview_field)

            readmore_field = models.CharField(editable=False, blank=True, null='', max_length=250)
            cls.add_to_class(_readmore_field_name(name), readmore_field)
        super(RichTextField, self).contribute_to_class(cls, name)
        setattr(cls,, MarkupDescriptor(self))

For example in my model i adding this type of fields by piece of code:

content = RichTextEditor()

All working good until i want to migrate this app :)

As result of migration i getting fields in migration file.

                ('content', project.apps.utils.fields.RichTextField()),
                ('_content_preview', models.TextField(null=b'', editable=False, blank=True)),
                ('_content_readmore', models.CharField(max_length=250, null=b'', editable=False, blank=True)),

This is ok, but when i start migration i getting error.

django.db.utils.ProgrammingError: column "_content_preview" specified more than once.

This error throwed because one time this field added from migration file and second time it added from field initialization for content field.

                ('content', project.apps.utils.fields.RichTextField()),

Does anybody have same problems? Thanks, alex.

You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To post to this group, send email to
Visit this group at
To view this discussion on the web visit
For more options, visit

No comments:

Post a Comment