更新到DRF 3.0和Django 1.8后,Serialiser方法无效

时间:2016-07-11 14:32:25

标签: django django-rest-framework

我不确定它是否相关。但在我更新到DRF 3.0和Django 1.8之前,我的以下代码工作正常。

class DialogueSerializer(serializers.ModelSerializer):

    sound_url = serializers.SerializerMethodField('get_sound_url')

    class Meta:
        model = Dialogue
        fields = ('id','english','myanmar', 'sound_url') 

    def get_sound_url(self, dialogue):
        if not dialogue.sound:
            return None

        request = self.context.get('request')
        sound_url = dialogue.sound.url
        return request.build_absolute_uri(sound_url)
有些人也这样说过。 https://github.com/lightweightdjango/examples/issues/2

现在,当我跑步时,我得到了

  

在SerializerMethodField上指定get_sound_url是多余的   ' sound_url'在序列化器' DialogueSerializer'中,因为它是相同的   作为默认方法名称。删除method_name参数。

enter image description here

我该怎么办?

1 个答案:

答案 0 :(得分:2)

由于您的字段为sound_url,而您的方法为get_field_nameget_sound_url),因此您无需向SerializerMethodField提供方法名称。

正如您在DRF documentation的示例中所看到的,在这种情况下无需精确method_name

from django.contrib.auth.models import User
from django.utils.timezone import now
from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    days_since_joined = serializers.SerializerMethodField()

    class Meta:
        model = User

    def get_days_since_joined(self, obj):
        return (now() - obj.date_joined).days

所以,结果是:

class DialogueSerializer(serializers.ModelSerializer):

    sound_url = serializers.SerializerMethodField() # no more `method_name` passed

    class Meta:
        model = Dialogue
        fields = ('id','english','myanmar', 'sound_url') 

    def get_sound_url(self, dialogue):
        if not dialogue.sound:
            return None

        request = self.context.get('request')
        sound_url = dialogue.sound.url
        return request.build_absolute_uri(sound_url)