I've been trying to modify the AuditTrail code so that it does not copy ForeignKey
fields, but rather copies the related field (ie I don't want a foreign key on my database table for the audit model).
I've written a copy_field
function that looks like so:
def copy_field(field):
while(isinstance(field, models.OneToOneField, models.ForeignKey)):
field = field.rel.get_related_field()
if isinstance(field, models.AutoField):
f = models.IntegerField()
else:
f = copy(field)
#...snip some adjusting of fs attributes...
return f
This code is run when the model that has the AuditTrail
attribute is prepared (via the class_prepared
signal).
However, this runs into problems when a ForeignKey
is related to a field on a model that has not been prepared yet - the get_related_field()
call will fail, because field.rel.to
is a string containing the name of the related model, rather than a model instance.
I'm at a loss of what to do to work around this. Do I have to determine what dependencies a model has, and wait until they have all been prepared, before I start copying fields? Any ideas about the best way to go about this?