Python 获取外键关系的对象以在Django中显示
此图像出现问题 我希望在框中显示VendorProfile名称而不是VendorProfile对象。我在VendorProfile中为PurchaseOrder使用外键关系。 以下是我在models.py中的代码:Python 获取外键关系的对象以在Django中显示,python,django,admin,Python,Django,Admin,此图像出现问题 我希望在框中显示VendorProfile名称而不是VendorProfile对象。我在VendorProfile中为PurchaseOrder使用外键关系。 以下是我在models.py中的代码: class PurchaseOrder(models.Model): product = models.CharField(max_length=256) vendor = models.ForeignKey('VendorProfile') class VendorP
class PurchaseOrder(models.Model):
product = models.CharField(max_length=256)
vendor = models.ForeignKey('VendorProfile')
class VendorProfile(models.Model):
name = models.CharField(max_length=256)
address = models.CharField(max_length=512)
city = models.CharField(max_length=256)
这是我在admin.py中的代码:
class PurchaseOrderAdmin(admin.ModelAdmin):
fields = ['product', 'dollar_amount', 'purchase_date','vendor', 'notes']
list_display = ('product','vendor', 'price', 'purchase_date', 'confirmed', 'get_po_number', 'notes')
那么,如何让它在两个字段和列表显示中显示供应商档案的“名称”?为返回名称的供应商档案
方法定义一个方法
从文档中:
每当您在对象上调用unicode()
时,就会调用\uuuuunicode\uuuuu()
方法。Django在许多地方使用unicode(obj)
(或相关函数str(obj)
)。最值得注意的是,在Django管理站点中显示对象,并在显示对象时作为插入到模板中的值。因此,您应该始终从\uuuuunicode\uuuuu()
方法返回一个漂亮的、人类可读的模型表示
为返回名称的VendorProfile
方法定义一个方法
从文档中:
每当您在对象上调用unicode()
时,就会调用\uuuuunicode\uuuuu()
方法。Django在许多地方使用unicode(obj)
(或相关函数str(obj)
)。最值得注意的是,在Django管理站点中显示对象,并在显示对象时作为插入到模板中的值。因此,您应该始终从\uuuuunicode\uuuuu()
方法返回一个漂亮的、人类可读的模型表示
最简单的方法是向类中添加一个unicode函数,返回要在下拉列表中显示的值:
class PurchaseOrder(models.Model):
product = models.CharField(max_length=256)
vendor = models.ForeignKey('VendorProfile')
def __unicode__(self):
return self.product
class VendorProfile(models.Model):
name = models.CharField(max_length=256)
address = models.CharField(max_length=512)
city = models.CharField(max_length=256)
def __unicode__(self):
return self.name
然后将在“管理”下拉列表中显示供应商名称。最简单的方法是向类中添加一个unicode函数,返回要在下拉列表中显示的值:
class PurchaseOrder(models.Model):
product = models.CharField(max_length=256)
vendor = models.ForeignKey('VendorProfile')
def __unicode__(self):
return self.product
class VendorProfile(models.Model):
name = models.CharField(max_length=256)
address = models.CharField(max_length=512)
city = models.CharField(max_length=256)
def __unicode__(self):
return self.name
然后将在“管理”下拉列表中显示供应商名称