使用request.user和django rest framework serializers

时间:2015-08-20 01:44:36

标签: django python-3.x django-views django-rest-framework

我目前正在首次使用django rest框架编写API。但是,在尝试仅使用request.user字段

更新对象时,我遇到了问题

据我所知,在使用request.data字段更新对象时,您所要做的就是:

def put(self, request, pk, format=None):
    chore = self.get_object(pk)
    serializer = ChoreSerializer(chore, data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

但是,如果我尝试将data = request.data保留,我在尝试调用.is_valid()时会出错。反过来.save()。我设法通过基于主键序列化我想要更改的对象,然后使用这样的序列化数据再次反序列化来解决此错误:

seri = ChoreSerializer(chore)
serializer = ChoreSerializer(chore, data=seri.data)

if serializer.is_valid():
    serializer.save(assigned_to=self.request.user)
    return Response(serializer.data)

我的问题是这实际上是否是正确的方法,或者是否有更好的方法

这是我的模特:

class Chore(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=100, blank=True, default='')
    owner = models.ForeignKey('auth.User', related_name='chores')
    assigned_to = models.ForeignKey('auth.User',related_name='assigned_to', blank=True, null=True)

这是我的Serializer:

class ChoreSerializer(serializers.ModelSerializer):

class Meta:
    model = Chore
    fields = ('id', 'name', 'owner', 'assigned_to')

owner = serializers.ReadOnlyField(source='owner.username')
assigned_to = serializers.ReadOnlyField(source='assigned_to.username')

def create(self, validated_data):
    return Chore.objects.create(**validated_data)

def update(self, instance, validated_data):
    instance.name = validated_data.get('name', instance.name)
    instance.assigned_to = validated_data.get('assigned_to', instance.assigned_to)
    instance.save()
    return instance

0 个答案:

没有答案