简体   繁体   中英

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?

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

Since you use the related_name more than once, in model classes you inherit, then related name for the user model is not clear and clashes.

You will have to set a different related_name for each model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM