Django models: mutual references between two classes and impossibility to use forward declaration in python

为君一笑 提交于 2019-11-29 16:47:29

问题


I have defined two models where each one references the other, like so:

class User(models.Model):
    # ...
    loves = models.ManyToManyField(Article, related_name='loved_by')

class Article(models.Model):
    # ...
    author = models.ForeignKey(User)

You see, the problem is both classes references each other. No matter in what order these two classes are implemented, python always raises NameError exception, complaining either one class is not defined.


回答1:


You can find the solution in the docs:

If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself:

class Car(models.Model):
    manufacturer = models.ForeignKey('Manufacturer')
    # ...

class Manufacturer(models.Model):
    # ...


来源:https://stackoverflow.com/questions/7298326/django-models-mutual-references-between-two-classes-and-impossibility-to-use-fo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!