本文介绍了Django models.py 循环外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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(删节):

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)

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

I get the same error when I switch the order of the classes in models.py except it says 'Album' undefined instead of 'Image' undefined I also tried commenting the dependancy in the first class then uncommenting after everything else was successfully imported but that didn't help. How should I go about making this work? I'm reluctant to make an entire third class Thumb because it will have a lot of the same code as Image I'm also pretty sure I could manually add the foreign key to the database but I want this to be clean and not hackish.

推荐答案

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

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)

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

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).

这篇关于Django models.py 循环外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 01:25