Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 531
koo Avatar asked Sep 04 '11 09:09

koo


1 Answers

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):
    # ...
like image 174
Benjamin Wohlwend Avatar answered Sep 21 '22 05:09

Benjamin Wohlwend