我在Django中有两个模型:
class Project(models.Model):
title = models.CharField(max_length=255)
client = models.CharField(max_length=255, blank=True, null=True)
...
class Task(models.Model):
title = models.CharField(max_length=255)
project = models.ForeignKey(Project)
...
我的serializer.py
class TaskSerializer(serializers.HyperlinkedModelSerializer):
project = serializers.RelatedField(
source='project'
)
client = ?
# I want to return just the project.client field
class Meta:
model = Task
fields = (
'id', 'project', 'title', 'client'
...
)
答案 0 :(得分:3)
字段的DRF source
参数支持虚线路径。 (见the docs)
所以你的client
字段将是:
client = serializers.RelatedField(
source='project.client'
)