鉴于以下模型:
class Project(models.Model):
project_name = models.CharField(max_length=255)
abstract = models.TextField(blank=True, null=True)
full_description = models.TextField(blank=True, null=True)
date_begun = models.DateField(blank=True, null=True)
related_projects = models.ManyToManyField('self', blank=True, null=True)
class Meta:
ordering = ['project_name']
def __unicode__(self):
return self.project_name
如何在related_projects字段中访问项目引用的ID。例如,我可以通过执行以下操作来获取project_name值:
def transform_related_projects(self, instance):
return [unicode(rp) for rp in instance.related_projects.all()]
但我无法看到如何获取项目记录的if,因为def unicode (self)函数仅将项目名称作为unicode字符串返回。我知道我错过了一些明显的东西。感谢
答案 0 :(得分:1)
def transform_related_projects(self, instance):
return [rp.id for rp in instance.related_projects.all()]