将内联模型添加到django管理站点

时间:2015-11-17 02:19:03

标签: python django foreign-keys django-admin

我有两个模型:

class Rule(models.Model):
    name = models.CharField(max_length=200)

class Channel(models.Model):

    id = models.CharField(max_length=9, primary_key=True)
    name = models.CharField(max_length=100)
    rule = models.ForeignKey(Rule, related_name='channels', blank=True)

我必须能够在RuleAdmin界面中的管理站点中添加规则。所以我创建了这两个管理模型:

class ChannelAdmin(admin.TabularInline):
    model = Channel

class RuleAdmin(admin.ModelAdmin):
    model = Rule
    inlines = [ChannelAdmin]

但是当我启动服务器时,我遇到了这个错误:

ERRORS:
<class 'main.admin.ChannelAdmin'>: (admin.E202) 'main.Channel' has no ForeignKey to 'main.Channel'.

仍然在django shell中,我可以进行像

这样的查询
rule = Rule.objects.get(pk=1)
rule.channels.all()

有一些明显的东西,但我无法理解。

2 个答案:

答案 0 :(得分:3)

做这样的事情:

class ChannelAdmin(admin.TabularInline):
    model = Channel

class RuleAdmin(admin.ModelAdmin):
   inlines = [ChannelAdmin,]

admin.site.register(Rule,RuleAdmin)

答案 1 :(得分:1)

class OrderItemInline(admin.TabularInline):
    model = OrderItem
    fields = ['image']    

class OrderAdmin(admin.ModelAdmin):
    list_display = ['id']
    list_filter = ['status']
    inlines = [OrderItemInline]