I want to add several fields to each model in my django application. This time it's created_at , updated_at and notes . Duplicate code for every 20 models seems dumb. So, I decided to use an abstract base class that will add these fields. The problem is that the fields inherited from the abstract base class are included in the list of fields in admin. Declaring the field order for each ModelAdmin class is not an option, it even duplicates the code than with the manual field instruction.
In my final solution, I modified the model constructor to override fields in _meta before creating a new instance:
class MyModel(models.Model): # Service fields notes = my_fields.NotesField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True last_fields = ("notes", "created_at", "updated_at") def __init__(self, *args, **kwargs): new_order = [f.name for f in self._meta.fields] for field in self.last_fields: new_order.remove(field) new_order.append(field) self._meta._field_name_cache.sort(key=lambda x: new_order.index(x.name)) super(MyModel, self).__init__(*args, **kwargs) class ModelA(MyModel): field1 = models.CharField() field2 = models.CharField() #etc ...
It works as intended, but I wonder if there is a better way to achieve my goal?
python django django-models
Alexander Lebedev
source share