Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating the related_name from META class

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"
like image 357
Prometheus Avatar asked Jun 01 '15 17:06

Prometheus


Video Answer


1 Answers

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.

like image 130
sthzg Avatar answered Oct 12 '22 03:10

sthzg