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): # ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With