Django Rest Framework从ForeignKey关系返回一个字段

时间:2014-06-06 20:55:01

标签: django django-rest-framework

我在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'
            ...
        )

1 个答案:

答案 0 :(得分:3)

字段的DRF source参数支持虚线路径。 (见the docs

所以你的client字段将是:

client = serializers.RelatedField(
    source='project.client'
)