Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple foreign key fields in abstract Django class

I have an abstract base class that declares two foreign key fields to the user model:

class BaseModel(models.Model):
    updated = models.DateTimeField(null=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="updated_by")
    created = models.DateTimeField(null=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="created_by")

    class Meta:
        abstract=True

I have multiple classes that inherit from this class. When I run makemigrations, I get the following error for each possible class-pair and for both created_by and updated_by:

myapp.ClassA.updated_by: (fields.E305) Reverse query name for 'ClassB.updated_by' clashes with reverse query name for 'ClassB.updated_by'.

HINT: Add or change a related_name argument to the definition for 'ClassA.updated_by' or 'ClassB.updated_by'.

Even though I already have a related_name set. It works fine with just one of the two foreign key fields declared.

Is it possible to have two foreign key fields to the same model in an abstract class, and if so, how do I set it up?

like image 264
ebug Avatar asked Jan 06 '23 13:01

ebug


1 Answers

This is the expected behavior as mentioned in the documentation.

To work around this problem, when you are using related_name in an abstract base class (only), part of the name should contain '%(app_label)s' and '%(class)s'.

class BaseModel(models.Model):
    updated = models.DateTimeField(null=True)
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="updated%(app_label)s_%(class)s_related")
    created = models.DateTimeField(null=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="created%(app_label)s_%(class)s_related")

    class Meta:
        abstract=True
like image 165
styvane Avatar answered Jan 15 '23 01:01

styvane