【问题标题】:django models cyclic importdjango模型循环导入
【发布时间】:2021-10-25 14:22:16
【问题描述】:

我已阅读有关相互进口问题的一些相关帖子(循环)。我正在开发一个 django 应用程序,这是我遇到问题的方式:

我有两个应用程序,第一个 articles,第二个 tags

我的文章模型有一个多对多字段,用来表示相关标签:

articles/models.py

from django.db import models
from tags.models import Tag

class Article(models.Model):
    tags = models.ManyToManyField(Tag)

但是,在我的tags 应用程序中,我还需要导入Article 模型来实现方法:

tags/models.py

from django.db import models
from articles.models import Article

# Create your models here.
class Tag(models.Model):
    title = models.CharField(max_length=100)
    content = models.CharField(max_length=255)

    def getAritcleLength():
        pass

    def getQuestionLength():
        pass

我通常使用模块来组合这些类定义,通常不会根据方法解析顺序遇到问题。但是,在 django 中,我们需要将类放入单独的文件夹中的工作流程,如果有任何建议,我将非常高兴。

【问题讨论】:

    标签: python django import


    【解决方案1】:

    Article模型中不要导入Tag模型,而是使用类的字符串引用。

    # articles/models.py
    
    from django.db import models
    
    
    class Article(models.Model):
        tags = models.ManyToManyField('Tag')    OR: you can use app_name.model_name format as well
    

    另一种方法是使用 Django 的方法从字符串中获取模型,然后使用该变量作为模型引用。 Django: Get model from string?

    【讨论】:

      【解决方案2】:

      尝试删除这个字符串

      from articles.models import Article
      

      【讨论】:

        猜你喜欢
        • 2020-07-11
        • 2021-04-06
        • 1970-01-01
        • 2023-03-12
        • 2018-12-25
        • 2014-03-10
        • 1970-01-01
        • 2023-02-18
        • 1970-01-01
        相关资源
        最近更新 更多