简体   繁体   English

抽象Django类中的多个外键字段

[英]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 : 当我运行makemigrations ,对于每个可能的类对以及created_byupdated_by都会收到以下错误:

myapp.ClassA.updated_by: (fields.E305) Reverse query name for 'ClassB.updated_by' clashes with reverse query name for 'ClassB.updated_by'. myapp.ClassA.updated_by :(字段E305)“ ClassB.updated_by”的反向查询名称与“ ClassB.updated_by”的反向查询名称发生冲突。

HINT: Add or change a related_name argument to the definition for 'ClassA.updated_by' or 'ClassB.updated_by'. 提示:在“ ClassA.updated_by”或“ ClassB.updated_by”的定义中添加或更改related_name参数。

Even though I already have a related_name set. 即使我已经设置了related_name。 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' . 若要解决此问题,当您在抽象基类(仅)中使用'%(app_label)s' ,部分名称应包含'%(app_label)s''%(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. 由于您多次使用related_name,因此在您继承的模型类中,用户模型的相关名称不明确且会冲突。

You will have to set a different related_name for each model. 您将必须为每个模型设置一个不同的related_name。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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