Django models: mutual references between two class

2019-02-11 19:34发布

问题:

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