gpt4 book ai didi

python - Django models.py 循环外键

转载 作者:IT老高 更新时间:2023-10-28 21:06:19 25 4
gpt4 key购买 nike

我有一个 django 应用程序,它基本上只是一个相册。现在我有两个模型:ImageAlbum。除其他外,每个 Album 都有一个指向 Image 的外键作为其缩略图,每个 Image 都有一个指向 的外键它所属的专辑。但是,当我尝试使用 manage.py syncdbmanage.py sqlall 时,我收到错误提示该类未在模型中首先定义.py 在定义的第一个类中使用时未定义。

models.py(删节):

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)

执行 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

当我在 models.py 中切换类的顺序时,我得到了同样的错误,除了它说 'Album' undefined 而不是 'Image' undefined 我也试过在第一个类中评论依赖关系,然后在其他所有内容成功导入后取消评论,但这没有帮助。我应该如何去做这项工作?我不愿意制作整个第三类 Thumb 因为它会有很多与 Image 相同的代码我也很确定我可以手动添加外键到数据库,但我希望它是干净的而不是hackish。

最佳答案

您实际上没有循环引用;问题是,在您定义专辑时,您还没有定义图像。你可以改用字符串来解决这个问题:

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

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

关于python - Django models.py 循环外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3682513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com