Most of my Django models use the same User Mixin, because of this I would like to dynamically create the related_name
for the field.
I would like it to be the class name where TestModel
becomes test_models
or maybe even a set name from the meta class on the main model.
I have looked at self__class__.__name__
but this give me the name of the User class.
Would it be possible to do something like below, if so how....
class User(models.Model):
user = models.ForeignKey(USER, related_name=META.related_name)
class Meta:
abstract = True
class TestModel(User):
title = models.CharField(max_length=80)
class Meta:
related_name = "test_model"
I think it might be sufficient to handle this like it is documented here.
# myapp/models.py
class User(models.Model):
user = models.ForeignKey(
USER,
related_name="%(app_label)s_%(class)s_related"
)
class Meta:
abstract = True
class TestModel(User):
title = models.CharField(max_length=80)
This way the related name would dynamically become myapp_testmodel_related
. Of course you can tweak the name and simplify the pattern, if it is certain that the names can't clash between multiple apps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With