You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Django模型定义中使用基于关联的数据

Django模型字符串表示关联外键数据的解决方法

问题描述

希望让Django模型的字符串表示显示关联(JOIN)的数据,例如Penciler模型的字符串表示要输出John Doe (DC)格式,其中publisher是ForeignKey字段,需要引用关联的Publisher模型的publisherName属性。

原代码存在的问题

  1. Publisher模型方法错误:定义的是__self__而不是正确的__str__方法,导致直接打印publisher对象时无法返回publisherName。
  2. Penciler模型__str__语法错误:返回语句写法不符合Python语法,无法正确拼接字符串。
  3. Series模型Meta配置错误:ordering指定的publication_year和title字段不存在,会导致运行报错。
  4. Series模型日期计算问题:直接用first_published - last_published会得到timedelta对象,显示不直观。

修正方案

方案1:修复Publisher的__str__方法,间接引用

先修正Publisher模型的字符串方法,这样在Penciler中直接调用self.publisher就能获取出版社名称:

from django.db import models

class Series(models.Model):
    seriesId = models.AutoField(primary_key=True)
    series_name = models.CharField(max_length=300)
    publisher = models.ForeignKey('Publisher', on_delete=models.PROTECT)
    first_published = models.DateField()
    last_published = models.DateField()
    discontinued = models.BooleanField(default=False)
    
    def __str__(self):
        # 计算出版时长并格式化显示
        publish_duration = (self.last_published - self.first_published).days
        return f'{self.series_name} - {self.publisher} (出版时长: {publish_duration}天)'
    
    class Meta:
        # 修正为模型存在的字段排序
        ordering = ['first_published', 'series_name']

class Publisher(models.Model):
    publisherId = models.AutoField(primary_key=True)
    publisherName = models.CharField(max_length=250, null=False)
    
    # 修正方法名为__str__,定义模型的字符串表示
    def __str__(self):
        return self.publisherName
    
class Penciler(models.Model):
    pencilerID = models.AutoField(primary_key=True)
    pencilerName = models.CharField(max_length=200)
    publisher = models.ForeignKey('Publisher', on_delete=models.PROTECT)
    
    def __str__(self):
        # 利用Publisher的__str__方法获取名称,拼接成目标格式
        return f'{self.pencilerName} ({self.publisher})'

方案2:直接访问关联模型的属性

如果不想依赖Publisher的__str__方法,可以直接访问关联对象的publisherName属性:

class Penciler(models.Model):
    # 其他字段定义不变
    def __str__(self):
        return f'{self.pencilerName} ({self.publisher.publisherName})'

内容的提问来源于stack exchange,提问作者Terry Brooks Jr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 05:55:15