Django多对多内联 - 如何显示通过模型引用的字段? [英] Django Many to Many Inline - how to show fields referenced by through model?
本文介绍了Django多对多内联 - 如何显示通过模型引用的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在django Admin中自定义和内嵌多个内联,但是我无法显示底层模型的字段。
I'm trying to customize and many to many inline in the django Admin, but I'm not able to display the fields of the underlying models.
这里是一个简化的例子。也许你可以告诉我如何引用它们?
Here's a simplified example. Maybe you can tell me how to reference them?
这是我的模型:
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)
(I'm on Django 1.6)
更新:
为什么这不工作。 (添加计算字段到模型。)
Update: Why won't this work either. (Added calculated field to through model.)
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',)
推荐答案
尝试这个。希望它解决你的问题
Try this. Hope it solves your problem
class ClownInline(admin.TabularInline):
model = WorkedAt
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',)
这篇关于Django多对多内联 - 如何显示通过模型引用的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文