Django rest框架返回非必填字段

时间:2017-09-03 22:10:50

标签: django-rest-framework

在我的序列化程序中,我有一个设置为非必需的字段。

当我序列化模型实例时,该字段不在输出中。

如何在输出中包含此字段?

class Client(models.Model):
    user = models.OneToOneField(User)
    profile_photo = models.ImageField(upload_to='pictures/profile_photos')
    phone = models.CharField(max_length=100, default="")

class ClientSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username')
    profile_photo = serializers.ImageField(source='details_sample.profile_photo', required=False)

    class Meta:
        model = Client
        fields = ('id', 'username', 'profile_photo', 'phone')


@api_view(['GET'])
def get_user_info(request):

    client = Client.objects.get(user=request.user)
    serialized = ClientSerializer(client)

    return Response(serialized.data) # no profile_photo

你能帮助我吗?

1 个答案:

答案 0 :(得分:0)

这应该有效:

class Client(models.Model):
    user = models.OneToOneField(User)
    profile_photo = models.ImageField(upload_to='pictures/profile_photos', null=True, blank=True)
    phone = models.CharField(max_length=100, default="")

class ClientSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username')

    class Meta:
        model = Client
        fields = ('id', 'username', 'profile_photo', 'phone')