Django models.py Circular Foreign Key Django models.py Circular Foreign Key python python

Django models.py Circular Foreign Key


You don't actually have a circular reference; the issue is that, at the time you define Album, you haven't defined Image yet. You can fix that by using a string instead:

class Album(models.model):  thumb = models.ForeignKey('Image', null=True, blank=True)

However, in this case, you might want to use a OneToOneField instead of a foreign key. (Note that you'll still have to use the trick with the string, though).


Use quotes to force a lazy reference:

models.ForeignKey('Image', null=True, blank=True)

Also, ForeignKey.related_name is your friend (avoids back-reference name clashes).


This is old but anyway, i'd like to say that I don't see a reason for attribute album in model Image. In my opinion, it is not really needed.