如果数据库中已存在以下项目:'email', 'youtube_channel_username', 'youtube_channel_url', 'youtube_channel_title'
,如何防止 POST 请求被保存?实际上,我想添加一个验证步骤,确保用户尝试发布的内容对于上述内容是唯一的。理想情况下,服务器应向用户发回错误消息,通知他们他们的请求因任何原因而失败。
到目前为止,这是我的代码。我不知道在哪里添加此功能,所以我将不胜感激!
serializers.py
class CreatorSignupSerializer(serializers.Serializer):
"""
Create Creator profile
"""
first_name = serializers.CharField(required=True, write_only=True)
last_name = serializers.CharField(required=True, write_only=True)
email = serializers.CharField(required=True, write_only=True)
youtube_channel_username = serializers.CharField(required=True, write_only=True)
youtube_channel_url = serializers.CharField(required=True, write_only=True)
youtube_channel_title = serializers.CharField(required=True, write_only=True)
youtube_channel_description = serializers.CharField(required=True, write_only=True)
photo = serializers.CharField(required=True, write_only=True)
youtube_channel_start_date = serializers.CharField(required=True, write_only=True)
keywords = serializers.CharField(required=True, write_only=True)
no_of_subscribers = serializers.IntegerField(required=True, write_only=True)
no_of_videos = serializers.IntegerField(required=True, write_only=True)
no_of_views = serializers.IntegerField(required=True, write_only=True)
no_of_likes = serializers.IntegerField(required=True, write_only=True)
no_of_dislikes = serializers.IntegerField(required=True, write_only=True)
location = serializers.CharField(required=True, write_only=True)
avg_views = serializers.IntegerField(required=True, write_only=True)
gender = serializers.IntegerField(required=True, write_only=True)
password = serializers.CharField(required=True, write_only=True)
class Meta:
model = Creator
fields = (
'first_name', 'last_name', 'email', 'youtube_channel_username', 'youtube_channel_url',
'youtube_channel_title', 'youtube_channel_description', 'photo', 'youtube_channel_start_date', 'keywords',
'no_of_subscribers', 'no_of_videos', 'no_of_views', 'no_of_dislikes', 'no_of_likes' 'location', 'avg_views',
'gender', 'password',
)
read_only_fields = 'id'
def create(self, validated_data):
creator = Creator.objects.create(**validated_data)
creator.save()
return creator
def update(self, instance, validated_data):
pass
views.py
class CreatorSignup(generics.CreateAPIView):
"""
Creator signup
HTTP POST
"""
queryset = Creator.objects.all()
serializer_class = CreatorSignupSerializer
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
return Response(data=serializer.data, status=status.HTTP_201_CREATED)
答案 0 :(得分:3)
您可以非常轻松地在模型级别实现独特验证。您只需要覆盖save以调用full_clean方法(如果您在模型级别进行任何其他验证)。此外,作为注释,它将抛出django.exceptions.ValidationError
并且您可以配置DRF以捕获django.exceptions.ValidationError
并将其转换为rest_framework.exceptions.ValidationError
,然后DRF将自动发回400错误消息。 / p>
# models.py
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=255, unique=True) # NOTE unique=True
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
phone = models.CharField(max_length=20)
def save(self, *args, **kwargs):
self.full_clean()
return super().save(*args, **kwargs)
答案 1 :(得分:2)
如何在模型的Meta类中添加>>> timeit.timeit('foo[stop_idx:start_idx+1][::-1]', setup='foo="012345"; stop_idx=0; start_idx=3', number=10_000_000)
1.7157553750148509
>>> timeit.timeit('foo[start_idx:stop_idx-len(foo)-1:-1]', setup='foo="012345"; stop_idx=0; start_idx=3', number=10_000_000)
1.9317215870250948
,如下所示
unique_together
注意:如果添加此项,则无需在序列化程序中定义任何特殊的验证方法