允许视图集中m2m字段的最大选择数量

问题描述 投票:-1回答:1

我想允许用户最多选择2个流派。我尝试添加models.py,但出现错误。现在,我正在考虑添加代码以检查views.py中所选择类型的数量,或者如果可能的话,可以在序列化器中。

class Story(models.Model):
    genre = models.ManyToManyField(Genre)
    def clean(self, *args, **kwargs):
         if self.genre.count() > 2:
             raise ValidationError('Error')
         super(Story, self).clean(*args, **kwargs)


class StorySerializer(serializers.ModelSerializer):
    genre = GenreSerializer(read_only=True, many=True)
    ...

class StoryView(viewsets.ModelViewSet):
    queryset = Story.objects.all()
    serializer_class = StorySerializer

    def perform_create(self, serializer):
        serializer.save(author=self.request.user)
python django django-models django-rest-framework
1个回答
0
投票

请参见https://docs.djangoproject.com/en/2.2/topics/db/examples/many_to_many/

问题是,您需要先将对象保存到数据库,然后才能创建多对多关系。试试这个:

def clean(self, *args, **kwargs):
         self.save()
         if self.genre.count() > 2:
             raise ValidationError('Error')
         super(Story, self).clean(*args, **kwargs)
© www.soinside.com 2019 - 2024. All rights reserved.