在Django管理页面中更改外键项的名称 [英] Changing name of Foreign Key items at admin page in Django

查看:485
本文介绍了在Django管理页面中更改外键项的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个Django模型,一个模型的字段是另一个模型的外键(如下所示)。

I have created two Django models, were a field from one model is a Foreign key to another (as per below).

class Units(models.Model):
    name = models.CharField(max_length=10, primary_key=True)
    symbol = models.CharField(max_length=5)


class Targets(models.Model):
    name = models.CharField(max_length=100)
    unit = models.ForeignKey(MicroNutrientUnits)
    ...

然后通过 admin.site.register 。将项目添加到表目标 unit 时,可以正确反映表Units中的项目,但是在下拉列表中以每个条目的名称​​ Units对象表示。

These models are then registered to the admin site via admin.site.register. When adding an item to table Target unit correctly reflects items from table Units, however are represented in a dropdown with the name Units objects for each entry.

如何在管理配置页面的管理下拉列表中将名称设置为 Units.name

How can I set the name in the admin dropdown to Units.name in the admin config page?

推荐答案

当我开始使用管理屏幕时,我遇到了同样的问题。我不知道是否有更好的方法可以执行此操作,但是我所做的是修改了models.py文件,以告知我的班级默认字符串返回什么。在您的情况下,我将在您的Units类定义中添加以下内容。

I had the same issue when I started playing with the admin screens. I don't know if there is a better way to do this but what I did was modify the models.py file to tell my classes what to return as a default string. In your case what I would do is add the following to your Units class definition.

class Units(models.Model):
    name = models.CharField(max_length=10, primary_key=True)
    symbol = models.CharField(max_length=5)

    def __str__(self):
        return self.name

这样,当您使用指向表的外键链接时,django将显示下拉列表中每个单元的名称,而不是一遍又一遍的单词 Units。

This way, when you use the foreign key link to the table, django will display the name of each unit in the dropdown list instead of just the word 'Units' over and over.

这篇关于在Django管理页面中更改外键项的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆