也可以使用 ContentType 设置 app_name 和 model_name 参见:https ://stackoverflow.com/a/11395481/991572
所以我最终这样做了webapp/models.py
:
from django.contrib.contenttypes.models import ContentType
from django.core import urlresolvers
class Base(models.Model):
title = models.CharField(max_length=100)
def _get_admin_url(self):
"Returns the admin change view url."
content_type = ContentType.objects.get_for_model(self.__class__)
view_name = "admin:%s_%s_change" % (content_type.app_label, content_type.model)
url = urlresolvers.reverse(view_name, args=(self.id,))
return url
admin_url = property(_get_admin_url)
class Book(Base):
something = models.CharField(max_length=100)
将 Base 和 Book 注册到管理站点,创建一些条目并在 shell 中:
In [1]: from webapp.models import *
In [2]: Base.objects.get(pk=1).admin_url
Out[2]: '/admin/webapp/base/1/'
In [3]: Book.objects.get(pk=2).admin_url
Out[3]: '/admin/webapp/book/2/'