Issue
I'd like to add to existing models new CharFields via one common mixin or abstract model but names of these fields depend on configuraton. so one model will have someprefix1_title field and another model - someprefix2_title.
Is it possible to make this approach to work:
class AbstractModel(models.Model):
self.fields_prefix + '_title' = models.CharField(max_length=255, blank=True, default='')
class Meta:
abstract = True
class ModelOne(AbstractModel):
fields_prefix = 'someprefix1'
id = models.AutoField(primary_key=True)
class ModelTwo(AbstractModel):
fields_prefix = 'someprefix2'
id = models.AutoField(primary_key=True)
so ModelOne could have fields id and someprefix1_title.
upd: what about monkey-patching with add_to_class() will it work or it's an antipattern and should not be used?
Solution
Try using a factory pattern to set up your different versions of AbstractModel
.
With this approach, you can more strictly control the way AbstractModel
is modified by way of the factory function dynamic_fieldname_model_factory
.
We're also not modifying ModelOne
or ModelTwo
after their definitions -- other solutions have pointed out that this helps avoid maintainability problems.
models.py:
from django.db import models
def dynamic_fieldname_model_factory(fields_prefix):
class AbstractModel(models.Model):
class Meta:
abstract = True
AbstractModel.add_to_class(
fields_prefix + '_title',
models.CharField(max_length=255, blank=True, default=''),
)
return AbstractModel
class ModelOne(dynamic_fieldname_model_factory('someprefix1')):
id = models.AutoField(primary_key=True)
class ModelTwo(dynamic_fieldname_model_factory('someprefix2')):
id = models.AutoField(primary_key=True)
Here is the migration generated by this code:
# Generated by Django 2.1.7 on 2019-03-07 19:53
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='ModelOne',
fields=[
('someprefix1_title', models.CharField(blank=True, default='', max_length=255)),
('id', models.AutoField(primary_key=True, serialize=False)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='ModelTwo',
fields=[
('someprefix2_title', models.CharField(blank=True, default='', max_length=255)),
('id', models.AutoField(primary_key=True, serialize=False)),
],
options={
'abstract': False,
},
),
]
Answered By - whp
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.