开发者

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

开发者 https://www.devze.com 2023-04-03 00:09 出处:网络
I have defined two models where each one references the other, like so: class User(models.Model): # ...

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.


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):
    # ...
0

精彩评论

暂无评论...
验证码 换一张
取 消