Django models.py Circular Foreign Key

jam*_*ate 17 python mysql django foreign-keys

I have a django app which basically is just a photo album. Right now I have two models: Image and Album. Among other things, each Album has a foreign key to an Image to be its thumbnail and each Image has a foreign key to the Album it belongs in. However, when I try to use manage.py syncdb or manage.py sqlall I get errors saying the class not defined first in models.py isn't defined when it is used in the first class defined.

models.py (abridged):

from django.db import models
import os

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

class Image(models.Model):
    image = models.ImageField(upload_to='t_pics/images')
    thumb = models.ImageField(upload_to='t_pics/images/thumbs')
    album = models.ForeignKey(Album)
Run Code Online (Sandbox Code Playgroud)

Error I get when I do manage.py sqlall appname:

[...]
 File "/path/to/file/appname/models.py", line 4, in ?
    class Album(models.Model):
  File "/path/to/file/appname/models.py", line 5, in Album
    thumb = models.ForeignKey(Image, null=True, blank=True)
NameError: name 'Image' is not defined
Run Code Online (Sandbox Code Playgroud)

我得到同样的错误,当我在切换的models.py类的顺序,除了上面说'Album' undefined的,而不是'Image' undefined我也试过在第一类,那么在取消后,其他一切都被成功导入,但没有帮助的评论扶养.我该怎么做才能做到这一点?我不愿意制作一个完整的第三类,Thumb因为它会有很多相同的代码,因为Image我也非常确定我可以手动将外键添加到数据库,但我希望这是干净而不是hackish.

mip*_*adi 38

你实际上没有循环引用; 问题在于,在您定义相册时,尚未定义图像.您可以通过使用字符串来修复它:

class Album(models.model):
  thumb = models.ForeignKey('Image', null=True, blank=True)
Run Code Online (Sandbox Code Playgroud)

但是,在这种情况下,您可能希望使用OneToOneField而不是外键.(注意,你仍然必须使用字符串的技巧).

  • 您的解决方案有效但我还必须将`related_name ='Image'添加到`Album.thumb`定义的参数中.OneToOneField优于ForeignKey的优势是什么? (2认同)

Pau*_*ine 12

使用引号强制执行惰性引用:

models.ForeignKey('Image', null=True, blank=True)
Run Code Online (Sandbox Code Playgroud)

此外,ForeignKey.related_name是您的朋友(避免反向引用名称冲突).

  • @puddingfox你意识到你可以改变选择的正确答案吗? (2认同)