I have read some relevant posts on the issue on mutual imports (circular). I am working on a django app, here's how I run to an issue:
I have two apps, first one articles
, second one tags
my article model have a many to many field, to indicate relevant tags:
articles/models.py
from django.db import models
from tags.models import Tag
class Article(models.Model):
tags = models.ManyToManyField(Tag)
however, in my tags
app, I also need to import Article
model to achieve the methods:
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
I usually use a module to combine those class definitions, normally won't run into issue according to method resolution order. However, in django the workflow we need to put classes into separated folders, I will be so glad for any suggestion.
CodePudding user response:
Try to delete this string
from articles.models import Article
CodePudding user response:
Don't import the Tag model in the Article model, but use the string reference of the class instead.
# 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
Another way is to use Django's method to get the model from a string and then use that variable in place for the model reference. Django: Get model from string?