在 django admin 中链接到外键对象 [英] Link in django admin to foreign key object
本文介绍了在 django admin 中链接到外键对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模型 A 和模型 B 的外键.在 Django admin 中,如何在模型 A 的管理页面中在打开模型 B 的管理页面的 ForeignKey 字段旁边添加一个链接?
I have a model A with a ForeignKey to a model B. In Django admin, how can I add a link in the admin page of model A next to the ForeignKey field which open the admin page of the model B ?
推荐答案
您可以执行以下操作:
models.py(示例):
models.py (example):
model B(models.Model):
name = models.CharField(max_length=20)
model A(models.Model):
field1 = models.CharField(max_length=20)
Bkey = models.ForeignKey(B)
admin.py
from django.core import urlresolvers
class AAdmin(admin.ModelAdmin):
list_display = ["field1","link_to_B"]
def link_to_B(self, obj):
link=urlresolvers.reverse("admin:yourapp_b_change", args=[obj.B.id]) #model name has to be lowercase
return u'<a href="%s">%s</a>' % (link,obj.B.name)
link_to_B.allow_tags=True
将 yourapp 替换为您的应用名称.
Replace yourapp with the name of your app.
这篇关于在 django admin 中链接到外键对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文