在 ModelForm Django 中显示外键属性
Displaying foreign key attributes in ModelForm Django
型号:
class Company(models.Model):
id = models.AutoField(primary_key = True)
name = models.CharField(max_length = 30)
parent = models.ForeignKey('self', null=True, blank=True)
表格:
class CompanyForm(forms.ModelForm):
class Meta:
model = Company
fields = ['name', 'parent']
当我查看表单的 'parent' 下拉列表时,我得到一个对象列表:
- 公司对象
- 公司对象
- 公司对象
- 公司对象
我想在下拉列表中显示对象的名称:
- 联合利华
- 通用磨坊
- 牛皮纸
- 优诺
我需要添加哪些代码行?
您必须实施 __unicode__
遗留方法,或者如果您是最新的,您将实施 __str__
方法,将 class 装饰为 python2兼容seen in the django 1.11 docs:
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Company(models.Model):
id = models.AutoField(primary_key = True)
name = models.CharField(max_length = 30)
parent = models.ForeignKey('self', null=True, blank=True)
def __str__(self):
return '%s' % self.name
2019 年,您将 probably/hopefully 在 python3 开始您的项目,并且能够省略所有 python 2/3 兼容性。
处理方式略有不同 in this post。在这里,他们将 class 的 str 属性 设置为他们想要显示的字段的值。不过不确定这是否有副作用。
型号:
class Company(models.Model):
id = models.AutoField(primary_key = True)
name = models.CharField(max_length = 30)
parent = models.ForeignKey('self', null=True, blank=True)
表格:
class CompanyForm(forms.ModelForm):
class Meta:
model = Company
fields = ['name', 'parent']
当我查看表单的 'parent' 下拉列表时,我得到一个对象列表:
- 公司对象
- 公司对象
- 公司对象
- 公司对象
我想在下拉列表中显示对象的名称:
- 联合利华
- 通用磨坊
- 牛皮纸
- 优诺
我需要添加哪些代码行?
您必须实施 __unicode__
遗留方法,或者如果您是最新的,您将实施 __str__
方法,将 class 装饰为 python2兼容seen in the django 1.11 docs:
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Company(models.Model):
id = models.AutoField(primary_key = True)
name = models.CharField(max_length = 30)
parent = models.ForeignKey('self', null=True, blank=True)
def __str__(self):
return '%s' % self.name
2019 年,您将 probably/hopefully 在 python3 开始您的项目,并且能够省略所有 python 2/3 兼容性。
处理方式略有不同 in this post。在这里,他们将 class 的 str 属性 设置为他们想要显示的字段的值。不过不确定这是否有副作用。