I am trying to dynamically generate a new model based on fields from an existing model. Both are defined in /apps/main/models.py . The existing model looks something like this:
from django.db import models class People(models.Model): name = models.CharField(max_length=32) age = models.IntegerField() height = models.IntegerField()
I have a list containing the names of the fields that I would like to copy:
target_fields = ["name", "age"]
I want to create a new model that has all the fields named in target_fields , but in this case they should be indexed ( db_index = True ).
I initially hoped that I could just iterate over the properties of the People class and use copy.copy to copy the field descriptions defined on it. Like this:
from copy import copy d = {} for field_name in target_fields: old_field = getattr(People, field_name) # alas, AttributeError new_field = copy(old_field) new_field.db_index = True d[field_name] = new_field IndexedPeople = type("IndexedPeople", (models.Model,), d)
I was not sure that copy.copy() ing Fields would work, but I did not go far enough to find out: the fields listed in the class definition are not really included as properties of the class object, I assume they are used for some machinists of the metaclass.
After scrolling through the debugger, I found some types of Field objects listed in People._meta.local_fields . However, this is not just a description, which can be copy.copy() ed and used to describe another model. For example, they include the .model property related to People .
How to create a field description for a new model based on a field of an existing model?