Django两个模型之间的关系

3

我很新于Django。

你能否提供一个模型的样板,说明如何使两个模型相互关联。

--下面是Section模型

from articles.models import Article
# Create your models here.
class Section(models.Model): 
    #associations
    user    = models.ForeignKey(settings.AUTH_USER_MODEL)
    article = models.ForeignKey(Article) #Article

--以下是文章模型
from sections.models import Section
User = settings.AUTH_USER_MODEL

# Create your models here.
class Article(models.Model):
    owner       =models.ForeignKey(User, null=False)
    sections = models.ManyToManyField( Section )

然而,我遇到了以下错误: ValueError: 无法创建“article”的表单字段,因为其相关模型“articles.models”尚未加载
谢谢大家
B

你在这里定义了一个循环导入. - Willem Van Onsem
1个回答

4

打破循环引用

您定义了一种循环引用方式:一个模块需要先导入另一个模块,而该模块先要实现这个模块,从而形成了循环。

在Django中,你不必使用类引用来创建ForeignKey,你可以使用指向正确模型的字符串。在这种情况下,Django框架将稍后解析它们。

例如,我们可以这样打破循环引用:

# sections/models.py

# <b>no</b> import from articles

# Create your models here.
class Section(models.Model): 
    #associations
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    # we use a string literal
    article = models.ForeignKey(<b>'articles.Article'</b>, on_delete=models.CASCADE)

然后在 articles/models.py 中:

# articles/models.py

from sections.models import Section
User = settings.AUTH_USER_MODEL

# Create your models here.
class Article(models.Model):
    owner = models.ForeignKey(User, null=False)
    sections = models.ManyToManyField(Section)

因此,我们在“sections/models.py”中不再导入“articles/models.py”,从而打破了循环引用。
请注意,在ForeignKey中需要指定on_delete,例如models.CASCADE。
Django的反向关系
对于这个特定的应用程序,似乎您在Section和Article之间建立了一个双重关系,实际上它只是一个关系,您不应该这样做。 Django会自动编写反向关系,您可能想要做的是给它一个适当的名称,例如:
# sections/models.py

# <b>no</b> import from articles

# Create your models here.
class Section(models.Model): 
    #associations
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    # we use a string literal
    article = models.ForeignKey(
        'articles.Article',
        on_delete=models.CASCADE,
        <b>related_name='sections'</b>
    )

并且针对articles/models.py

# articles/models.py

User = settings.AUTH_USER_MODEL

# Create your models here.
class Article(models.Model):
    owner = models.ForeignKey(User, null=False)
    # <i>no</i> relation to section

我们可以使用 some_article.sections.all() 来获取与 some_article 相关的所有 Section


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接