在Django管理页面中更改外键项的名称

编程入门 行业动态 更新时间:2024-10-25 07:28:29
本文介绍了在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管理页面中更改外键项的名称

本文发布于:2023-11-12 01:02:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580059.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:名称   页面   Django   外键项

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!