Django models.py Circular Foreign Key

£可爱£侵袭症+ 提交于 2019-12-01 15:01:46

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!