我有一个多对多字段,我将其显示在 django 管理面板中。当我添加多个项目时,它们都在显示选择器中显示为“ASGGroup 对象”。相反,我希望它们以 ASGGroup.name 字段设置的形式出现。我该怎么做?
我的模型看起来像:
class Thing(Model):
read_groups = ManyToManyField('ASGGroup', related_name="thing_read", blank=True)
class ASGGroup(Model):
name = CharField(max_length=63, null=True)
但是我看到的 m2m 小部件显示是:
最佳答案
您需要在模型上定义 __unicode__
(或 __str__
如果您使用的是 Python 3)方法,因此:
class ASGGroup(Model):
name = CharField(max_length=63, null=True)
def __unicode__(self):
return self.name
现在,当您的模型被解析为字符串时,它将返回模型的 name
字段,而不是类名称。
关于python - Django:管理界面中多对多项目的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25431079/