I recommend using only a simple function to create a similarly pre-configured instance of ForeignKey: (and not an instance of a subclass of ForeignKey)
def pan_machine_time_unit_field(**kwargs): othermodel = 'panbas.PanBasTimeUnit' on_delete = models.DO_NOTHING
The related_name attribute is the name used to inverse relationship from the othermodel target to all objects that reference it. This name must be unique to othermodel ("panbas.PanBasTimeUnit", usually something with a unique name for the application and class), or this name can be '+' if you do not want to create a set of feedback requests. Both options are implied in this example. Also remember on_delete .
If you really need to create a subclass (which makes sense if you need to configure additional methods), you must also define a deconstruct method for the transfer. It would be difficult if you subsequently had to modify such a subclass. It cannot be deleted, renamed, etc. Due to migration in a custom field . On the other hand, if you create a simple ForeignKey instance directly using a function, you can ignore everything about migration.
EDIT
Alternatively, you can create an abstract base model with this field and create new models for inheritance or multiple inheritance :
class WithPanBasTimeUnit(models.Model): machine_unit = models.ForeignKey( 'panbas.PanBasTimeUnit', models.DO_NOTHING, verbose_name=_('Machine Unit'), related_name='%(app_label)s_%(class)s_related' ) class Meta: abstract = True class ExampleModel(WithPanBasTimeUnit, ...or more possible base models...): ... other fields
This solution (inspired by the invalid soution Ykh) is useful if you want to add a method to models with this field or add more fields together, otherwise the original solution will be simpler.
hynekcer
source share