处理具有带有多个外键的序列化程序的视图集

时间:2018-09-24 19:22:39

标签: django-rest-framework django-rest-viewsets

我有这个序列化器:

class ReviewSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)

    class Meta:
        model = Review
        fields = ('pk', 'title', 'user', 'movie', 'timestamp', 'review_text',)

我想提到usermovie都是ForeignKey中为models.py模型定义的Review。这是模型:

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)

我想创建一个视图集,但是如果我做这样的事情:

class ReviewsViewSet(viewsets.ModelViewSet):
    queryset = Movie.objects.all()
    serializer_class = ReviewSerializer

并这样注册:

router.register(r'reviews', views.ReviewsViewSet, 'reviews')

不起作用,它要求我提供一个movie field,如此处所记录:

AttributeError at /api/reviews/
Got AttributeError when attempting to get a value for field `movie` on serializer `ReviewSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Movie` instance.
Original exception text was: 'Movie' object has no attribute 'movie'.

谢谢。

已编辑。

0 个答案:

没有答案