问题描述
我具有用于评分课程的以下代码,应该从请求授权和URL中自动添加用户和课程:
I have this code for rating lessons, user and lesson should be added automatically from request authorization and URL:
#views.py
class RatingViewSet(
mixins.ListModelMixin,
mixins.CreateModelMixin,
viewsets.GenericViewSet
):
permission_classes = [permissions.IsAuthenticated]
serializer_class = RatingSerializer
def perform_create(self, serializer):
lessonInstance = Lesson.objects.get(id = self.kwargs['lessonID'])
serializer.save(user=self.request.user, lesson = lessonInstance)
def get_queryset(self):
lessonID = self.kwargs['lessonID']
return Rating.objects.filter(user=self.request.user, lesson=lessonID)
#serializers.py
class RatingSerializer(serializers.ModelSerializer):
class Meta:
model = Rating
fields = ('id', 'lesson','user', 'difficulty')
read_only_fields = ('id', 'user','lesson')
#models.py
class Rating(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
lesson = models.ForeignKey('lessons.Lesson')
difficulty = models.IntegerField()
class meta:
unique_together('user','lesson')
我希望每个用户/课程最多获得1个评分,因此 unique_together('user','lesson')
。但是存在一个问题:只要代码中存在该约束,没有 user
或 lesson
字段的请求都会被拒绝带有必填字段
的错误,即使它们是 read_only
。
I want to have max 1 rating per user/lesson, hence unique_together('user','lesson')
. But there is a problem: as long as that constraint is in the code, requests without user
or lesson
fields get denied with field required
error, even though they are read_only
.
(如果我使用 unique_together('user','lesson')
进行迁移,则删除该行即可,但是一旦出现该行,我就会报错。)
(If I migrate with unique_together('user','lesson')
, then delete that line it works, but as soon as it's there I get errors.)
我想在那儿保留那段代码,所以我不会在以后的迁移中不小心删除 unique_together
约束。
I want to keep that bit of code there so I don't accidentally remove the unique_together
constraint on later migrations.
推荐答案
这是特例,需要使用其他方法。这是 django-rest-framework
(请参见注释)说明这种情况:
This is a special-case that requires a different approach. Here's what django-rest-framework
documentation (see the Note) says about this case:
在您的情况下,您需要明确定义用户
和 RatingSerializer
上的用户课程
字段,例如:
In your case, you need to explicitly define the user
and lesson
fields on your RatingSerializer
, like this:
class RatingSerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) # gets the user from request
lesson = serializers.PrimaryKeyRelatedField(read_only=True, default=None) # or any other appropriate value
class Meta:
model = Rating
fields = ('id', 'lesson','user', 'difficulty')
祝你好运!
这篇关于两个字段的unique_together与read_only_fields混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!