[英]Django | Admin display foreign key as field rather than object
I have a Django project with the following two models setup:我有一个 Django 项目,具有以下两个模型设置:
class List(models.Model):
team = models.ForeignKey(Team, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
class ListItem(models.Model):
team_list = models.ForeignKey(List, on_delete=models.CASCADE)
content = models.TextField()
index = models.IntegerField()
I have them registered in my admin as follows:我让他们在我的管理员中注册如下:
class ListAdmin(admin.ModelAdmin):
list_display = ('team_name', 'name')
def team_name(self, obj):
return obj.team.name
admin.site.register(List, ListAdmin)
class ListItemAdmin(admin.ModelAdmin):
list_display = ('team', 'team_list_name', 'index')
def team(self, obj):
return obj.team_list.team.name
def team_list_name(self, obj):
return obj.team_list.name
admin.site.register(ListItem, ListItemAdmin)
This is great because now when I am looking at all of my "List items" in Django Admin, I can readily see the name of the list each item belongs to.这很棒,因为现在当我在 Django Admin 中查看我的所有“列表项目”时,我可以很容易地看到每个项目所属的列表名称。
However, when I am adding a new list item in admin I can only view the lists as an object (EX: "List Object (1)").但是,当我在管理员中添加新列表项时,我只能将列表视为 object(例如:“列表 Object (1)”)。 How can I make it so that the dropdown menus for foreign keys will display an object field rather than the object type?如何使外键的下拉菜单显示 object 字段而不是 object 类型?
The string used in the drop-down will come from the __str__
method in the relevant object.下拉列表中使用的字符串将来自相关 object 中的__str__
方法。 So to correct this, all you need to do is update your model:所以要纠正这个问题,您需要做的就是更新您的 model:
class List(models.Model):
team = models.ForeignKey(Team, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
def __str__(self):
# Return a string that represents the instance
return f"List {self.name}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.