0

我有这个序列化程序:

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

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

我想提一下,user并且movie都是在模型ForeignKey中定义的models.pyReview这是模型:

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'.

提前致谢。

已编辑。

4

0 回答 0