Django休息框架更新RelatedField

时间:2017-07-03 10:18:26

标签: django django-rest-framework

我有两种模式:

class PrdLine(models.Model):
    name = models.CharField(max_length=256, verbose_name='name', unique=True)
    comment = models.CharField(max_length=256, null=True, blank=True, verbose_name='comment')

    class Meta:
        verbose_name = 'prdline'
        verbose_name_plural = verbose_name


class Project(models.Model):
    name = models.CharField(max_length=256, verbose_name='name')
    prdline = models.ForeignKey(PrdLine, on_delete=models.CASCADE, verbose_name='prdline')
    comment = models.CharField(max_length=256, null=True, blank=True, verbose_name='comment')

    class Meta:
        unique_together = (('name', 'prdline'),)
        verbose_name = 'project'
        verbose_name_plural = verbose_name

我实现了一个自定义关系字段“PrdLineField”:

class PrdLineSerializer(ModelSerializer):

    links = serializers.SerializerMethodField()
    # id = serializers.IntegerField(required=False)

    class Meta:
        model = PrdLine
        fields = ('id', 'name', 'comment', 'links')

    def get_links(self, obj):
        request = self.context['request']
        return {
            'self': reverse('prdline-detail',
                            kwargs={'pk': obj.pk}, request=request)
        }


class PrdLineField(serializers.RelatedField):
    def to_representation(self, value):
        return {'id': value.id, 'name': value.name}

    def to_internal_value(self, data):
        return data

    def get_queryset(self):
        queryset = self.queryset
        if isinstance(queryset, (QuerySet, Manager)):
            queryset = queryset.all()
        print(queryset)
        return queryset


class ProjectSerializer(ModelSerializer):

    links = serializers.SerializerMethodField()
    prdline = PrdLineField(label='prdline', )

    class Meta:
        model = Project
        fields = ('id', 'name', 'prdline', 'comment', 'links')

    def get_links(self, obj):
        request = self.context['request']
        return {
            'self': reverse('project-detail',
                            kwargs={'pk': obj.pk}, request=request)
        }

    def create(self, validated_data):
        prdline = validated_data.pop('prdline', None)
        project = Project(**validated_data)
        project.prdline_id = prdline
        project.save()
        return project

    def update(self, instance, validated_data):
        prdline_id = validated_data.pop('prdline', None)['id']
        setattr(instance, 'prdline_id', prdline_id)
        for attr, value in validated_data.items():
                setattr(instance, attr, value)
        instance.save()
        return instance

如果我访问项目列表,字段'prdline'的效果就可以了:

[{
        "id": 10,
        "name": "eeeee",
        "prdline": {
            "name": "xxxxxxx",
            "id": 1
        },
        "comment": "",
        "links": {
            "self": "http://192.168.154.133:9090/api/projects/10"
        }
    }]

我可以用以下json创建一个项目:

{
    "name": "xxxxxx",
    "prdline": 2,
    "comment": "dddddd"
}

但是我无法通过上面的json更新项目,你必须使用:

{
    "id": 10,
    "name": "eeeee",
    "prdline": {
        "name": "xxxxxxxx",
        "id": 6
    },
    "comment": ""
}

我可以使用以下json来更新项目吗?

{
        "id": 10,
        "name": "eeeee",
        "prdline": 6
        "comment": ""
}

感谢您的帮助!

0 个答案:

没有答案