Django多对多内联 - 如何显示通过模型引用的字段?

时间:2014-02-04 20:25:43

标签: django django-forms django-admin django-1.6

我正在尝试在django Admin中自定义多个内联,但我无法显示基础模型的字段。

这是一个简化的例子。也许你可以告诉我如何引用它们?

以下是我的模特:

class Clown(models.Model):
    name = models.CharField(max_length=255)
    def edit_link(self):
        return ...

class Circus(models.Model):
    clowns = models.ManyToManyField(Clown, blank=True, through='WorkedAt')
    name = models.CharField(max_length=255)

class WorkedAt(models.Model):
    clown = models.ForeignKey(Clown)
    circus = models.ForeignKey(Circus)

和我的管理员:

class ClownInline(admin.TabularInline):
    model = WorkedAt
    fields = ['clown__name','clown__edit_link']


class CircusAdmin(admin.ModelAdmin):
    inlines = [
        ClownInline,
    ]
    exclude = ('clowns',)

但是我收到了这个错误:

Unknown field(s) (clown__name) specified for WorkedAt

(我在Django 1.6上)

更新 为什么这也不行。 (通过模型添加计算字段。)

class Clown(models.Model):
    name = models.CharField(max_length=255)
    def edit_link(self):
        return ...

class Circus(models.Model):
    clowns = models.ManyToManyField(Clown, blank=True, through='WorkedAt')
    name = models.CharField(max_length=255)

class WorkedAt(models.Model):
    clown = models.ForeignKey(Clown)
    circus = models.ForeignKey(Circus)
    @property
    def edit_link(self):
        return self.clown.edit_link()

和我的管理员:

class ClownInline(admin.TabularInline):
    model = WorkedAt
    fields = ['edit_link']


class CircusAdmin(admin.ModelAdmin):
    inlines = [
        ClownInline,
    ]
    exclude = ('clowns',)

2 个答案:

答案 0 :(得分:3)

试试这个。希望它能解决你的问题

class ClownInline(admin.TabularInline):
    model = WorkedAt
    fields = ['clown_name', 'clown_edit_link']
    readonly_fields = ['clown_name', 'clown_edit_link']

    def clown_name(self, instance):
        return instance.clown.name
    clown_name.short_description = 'clow name'

    def clown_edit_link(self, instance):
        url = reverse("admin:%s_%s_change" % (instance.clown._meta.app_label, instance.clown._meta.module_name), args=(instance.clown.pk,))
        return '<a href="%s">%s</a>' % (url, instance.clown.name)
    clown_edit_link.allow_tags = True


class CircusAdmin(admin.ModelAdmin):
    inlines = [
        ClownInline,
    ]
    exclude = ('clowns',)

答案 1 :(得分:1)

我不知道是否还有人需要这个,因为这个问题已经有4年了,但这解决了我在Django 2.0.3的问题:

# models.py
class Clown(models.Model):
    name = models.CharField(max_length=255)
    def edit_link(self):
        return ...


class Circus(models.Model):
    clowns = models.ManyToManyField(Clown, blank=True, through='WorkedAt')
    name = models.CharField(max_length=255)


class WorkedAt(models.Model):
    clown = models.ForeignKey(Clown)
    circus = models.ForeignKey(Circus)


# admin.py
class WorkedAtInline(admin.TabularInline):
    model = WorkedAt
    extra = 1


class WorkedAtAdmin(admin.ModelAdmin):
    inlines = (WorkedAtInline,)


admin.site.register(Clown, WorkedAtAdmin)

希望这可以帮助任何偶然发现这个问题的人并研究这个答案。