我不知道如何将用户对象传递给以下序列化器:
class ReviewSerializer(serializers.ModelSerializer):
user = UserSerializer(read_only=True)
class Meta:
model = Review
fields = ('pk', 'title', 'user', 'movie', 'timestamp', 'review_text',)
我有这个观点集:
class ReviewsViewSet(viewsets.ModelViewSet):
queryset = Review.objects.all()
serializer_class = ReviewSerializer
和此模型:
class Review(models.Model):
title = models.CharField(max_length=255)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='reviews')
movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name='reviews')
review_text = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '{movie} review by {user}'.format(user=self.user, movie=self.movie)
我的JavaScript请求如下:
return axios({
method: 'post',
url: 'http://localhost:8000/api/reviews/',
data: { // Using data from Vue
title: this.review_title,
movie: this.id,
review_text: this.review_text,
user: JSON.stringify(this.user)
},
headers: {
'Content-Type': 'application/json',
Authorization: `JWT ${token}`
}
})
它给了我this traceback。
如何将用户对象传递给请求?
谢谢。
答案 0 :(得分:2)
从序列化程序中删除 read_only=True
class ReviewSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = Review
fields = ('pk', 'title', 'user', 'movie', 'timestamp', 'review_text',)
如果设置了 read_only=True
,则DRF 将不会从输入源中获取值 ,即使该值存在
From the doc,
API输出中包含只读字段,但不应包含 在创建或更新操作期间包含在输入中。任何 错误地包含在序列化器中的“ read_only”字段 输入将被忽略。
将此设置为
True
,以确保序列化 表示形式,但在创建或更新实例时不使用 在反序列化期间。默认为
False
更新
您应将 create()
的 ReviewSerializer
方法改写为
class ReviewSerializer(serializers.ModelSerializer):
user = UserSerializer()
def create(self, validated_data):
user_dict = validated_data.pop('user')
user_obj, created = User.objects.get_or_create(**user_dict)
return Review.objects.create(user=user_obj, **validated_data)
class Meta:
model = Review
fields = ('pk', 'title', 'user', 'movie', 'timestamp', 'review_text',)
仅用于调试目的
class ReviewsViewSet(viewsets.ModelViewSet):
queryset = Review.objects.all()
serializer_class = ReviewSerializer
def create(self, request, *args, **kwargs):
print(request.data) # print here <<<<
return super(ReviewsViewSet, self).create(request, *args, **kwargs)