DjangoRestFramework - 如何序列化特定的ForiegnKey字段而不是PK值

时间:2015-11-05 22:53:53

标签: django django-rest-framework

这是我的模特:

class Post(models.Model):
    owner = models.ForeignKey(User, related_name="%(app_label)s%(class)s_set")
    usersVoted = models.ManyToManyField(User, blank=True)
    post = models.CharField(max_length=400)

这是我的序列化器:

class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = ('owner', 'usersVoted', 'post')
        read_only_fields = ('owner', 'usersVoted')

    def create(self, validated_data):
        drop = Drop(
                owner =  User.objects.get(username='TestUser'),
                post = validated_data['post'],
        )

所有者对默认的Django User模型有一个ForeignKey。目前,当我序列化帖子时,所有者是用户的pk值。如何让所有者成为用户的用户名?

2 个答案:

答案 0 :(得分:0)

你可以这样做:

class PostSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source="owner.username")

    class Meta:
        model = Post
        fields = ('owner', 'usersVoted', 'post')
        read_only_fields = ('owner', 'usersVoted')

    def create(self, validated_data):
        drop = Drop(
                owner =  User.objects.get(username='TestUser'),
                post = validated_data['post'],
        )

答案 1 :(得分:0)

如果用户名是唯一的,您应该使用SlugRelatedField。这将使字段读/写非常方便。 文档位于http://www.django-rest-framework.org/api-guide/relations/#slugrelatedfield