在Django内联管理:没有ForeignKey

时间:2014-02-20 06:04:32

标签: python django

我有两个Django模型:

class Author(models.Model):
    user_email =  models.CharField(max_length=100, blank=True)
    display_name =  models.CharField(max_length=250)

class Photo(models.Model):
    author = models.ForeignKey(Author)
    image = ThumbnailImageField(upload_to='photos')

要获取内联照片,我有admin.py:

class PhotoInline(admin.StackedInline):
    model = Author

class AuthorAdmin(admin.ModelAdmin):
    list_display = ('display_name','user_email')
    inlines = [PhotoInline]

我收到错误:Exception at /admin/metainf/author/11/

<class 'metainf.models.Author'> has no ForeignKey to <class 'metainf.models.Author'>

为什么?

3 个答案:

答案 0 :(得分:10)

内联模型应该具有到父模型的ForeignKey。要在Photo Author内联class PhotoInline(admin.StackedInline): model = Photo class AuthorAdmin(admin.ModelAdmin): list_display = ('display_name','user_email') inlines = [PhotoInline] ,您的模型代码就可以了。但您的管理代码应如下所示:

{{1}}

阅读更多信息here

答案 1 :(得分:2)

那是因为Author没有照片的外键。我认为你需要像这样切换内联模型:

class PhotoInline(admin.StackedInline):
    model = Photo

class AuthorAdmin(admin.ModelAdmin):
    list_display = ('display_name','user_email')
    inlines = [PhotoInline]

答案 2 :(得分:0)

也许您需要安装django-nested-admin库,然后再尝试使用NestedStackedInline。 django-nested-admin