Django后台如何在Process模型显示关联模型的名称字段?
Django Process模型后台显示自定义格式内容的解决方法
直接在Process模型中重写__str__方法即可,利用外键关联的对象属性拼接成你需要的格式:
方法一:直接调用关联对象的名称字段
class Process(models.Model): codeP = models.ForeignKey(Product, on_delete=models.CASCADE) codePart = models.ForeignKey(Part, on_delete=models.CASCADE) def __str__(self) -> str: # 拼接Product的nameP和Part的namePart return f"{self.codeP.nameP} - {self.codePart.namePart}"
方法二:利用已重写的__str__方法(更简洁)
因为你已经在Product和Part模型中重写了__str__方法,返回的是对应名称字段,所以可以直接使用外键对象本身,它会自动调用对应模型的__str__返回名称:
def __str__(self) -> str: return f"{self.codeP} - {self.codePart}"
两种方法都能让Django后台管理界面中,Process模型的实例显示为[产品名称] - [零件名称]的格式。
内容的提问来源于stack exchange,提问作者Lay N
相关产品推荐
相关产品推荐

