问题描述
我将Django管理员设置为以下型号:
class Quote(models.Model):
author = models.CharField(max_length = 100)
quote = models.CharField(max_length = 1000)
tags = models.ManyToManyField('Tag')
class标签(models.Model):
name = models.CharField(max_length = 100)
With以下代码:
class TagInline(admin.TabularInline):
model = Tag
类QuoteAdmin(admin.ModelAdmin):
list_display =( 'author','quote')
inlines =(TagInline,)
class TagAdmin(admin.ModelAdmin):
pass
admin.site 。$ {$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $> $>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>当尝试查看管理页面以添加引用
时,该页面显示错误,说< class'quotes.models.Tag'>没有ForeignKey到< class'quotes.models.Quote'>
。在我添加内联之前没有发生。有什么问题?如何正确添加标签
作为内联?
(我花了20分钟的时间搜索对于一个答案,我发现类似的问题,但他们的答案都没有为我工作。)
解决方案 有一个部分致力于建立多对多关系。您应该使用 Quote.tags.through
作为 TagInline
的模型,而不是标签
本身。
I'm setting up the Django admin to the following models:
class Quote(models.Model):
author = models.CharField(max_length=100)
quote = models.CharField(max_length=1000)
tags = models.ManyToManyField('Tag')
class Tag(models.Model):
name = models.CharField(max_length=100)
With the following code:
class TagInline(admin.TabularInline):
model = Tag
class QuoteAdmin(admin.ModelAdmin):
list_display = ('author', 'quote')
inlines = (TagInline,)
class TagAdmin(admin.ModelAdmin):
pass
admin.site.register(Quote, QuoteAdmin)
admin.site.register(Tag, TagAdmin)
When trying to view the admin page to add a Quote
, the page shows an error saying <class 'quotes.models.Tag'> has no ForeignKey to <class 'quotes.models.Quote'>
. This didn't happen before I added an inline. What's the problem? How do I correctly add a Tag
as an inline?
(I spent a good 20 minutes searching for an answer; I found similar questions but none of their answers worked for me.)
解决方案 Admin documentation has a section dedicated to inlining with many-to-many relationships. You should use Quote.tags.through
as a model for TagInline
, instead of Tag
itself.
这篇关于Django admin ManyToMany inline“没有ForeignKey to”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!