在不改变模型的情况下,最简单的解决方案可能是添加一个
parent
方法,并使用它而不是
list_display
列表:
class MyMenu(admin.ModelAdmin):
# ....
def parent(self, obj):
if obj.parent_id:
return Menu.objects.get(pk=obj.parent_id).cat_title
return ""
list_display = ('cat_title', 'menu_title', 'parent', 'level')
# Unrelated but you may also want to rewrite `get_choices`
# in a simpler and more performant way:
def get_choices(self):
choices = models.Menu.objects.values_list("id", "cat_title"))
return (('',''),) + tuple(choices)
或使
父母亲
您的
Menu
class Menu(models.Model):
# ...
# you may want to use django's `cached_property` instead
# but then you'll have to invalidate the cache when setting
# (or unsetting) `.parent_id`
@property
def parent(self):
if not self.parent_id:
return None
return Menu.objects.get(pk=self.parent_id)
列表显示
.
但是自从
Menu.parent_id
实际上是外键
菜单
,正确的解决方案是在模型中声明:
class Menu(models.Model):
cat_title = models.CharField(max_length=150, verbose_name='Category title')
menu_title = models.CharField(max_length=150, verbose_name='Menu title')
parent = models.ForeignKey("self", blank=True, null=True, related_name="children")
# etc