gpt4 book ai didi

django - 仅在创建新帖子时运行序列化程序的验证

转载 作者:行者123 更新时间:2023-12-03 10:41:40 26 4
gpt4 key购买 nike

我有 2 个 View - 其中一个使用 create另一个使用 RetrieveUpdateDestroyAPIView .两者都使用相同的 Serializer 类。我只在创建新帖子时需要标题验证,而不是在更新帖子时。
当我使用“PUT”请求更新某些帖子时,出现标题验证错误。
我怎样才能解决这个问题?

class StoreApiView(mixins.CreateModelMixin, generics.ListAPIView):
lookup_field = 'pk'
serializer_class = ProductSerializer

def get_queryset(self):
qs = Product.objects.all()
query = self.request.GET.get('q')
if query is not None:
qs = qs.filter(
Q(title__icontains=query) |
Q(description__icontains=query)
).distinct()
return qs

def perform_create(self, serializer):
serializer.save(author=self.request.user)

def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)


class StoreRucView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'pk'
serializer_class = ProductSerializer
permission_classes = [IsOwnerOrReadOnly]


def get_queryset(self):
return Product.objects.all()

这是序列化器类的完整代码:
class ProductSerializer(ModelSerializer):
product_ratings = ProductRatingSerializer(many=True,read_only=True)
product_badges_set = ProductBadgesSerializer(many=True,read_only=True)

author = serializers.SerializerMethodField()
category = serializers.SerializerMethodField()

def get_author(self, obj):
return obj.author.first_name+' '+obj.author.last_name

def get_category(self, obj):
return obj.category.title

class Meta:
model = Product
fields = [
'product_id',
'author',
'category',
'title',
'description',
'price',
'level',
'video_length',
'created_date',
'updated_date',
'product_ratings',
'product_badges_set',
]
read_only_fields = ['product_id', 'created_date', 'updated_date', 'author']

def validate_title(self, value):

qs = Product.objects.filter(title__iexact=value)
if self.instance:
qs.exclude(pk=self.instance.pk)
if qs.exists():
raise serializers.ValidationError("this title is already used")
return value

最佳答案

您可以通过additional context在序列化器中。并在 validate_title 中检查此上下文的值.鉴于:

def get_serializer_context(self):
context = super().get_serializer_context()
context['is_create'] = True
return context

def perform_create(self, serializer):
serializer.save(author=self.request.user)

在序列化器中:
def validate_title(self, value):
if self.context.get('is_create'):
qs = Product.objects.filter(title__iexact=value)
if self.instance:
qs.exclude(pk=self.instance.pk)
if qs.exists():
raise serializers.ValidationError("this title is already used")
return value

关于django - 仅在创建新帖子时运行序列化程序的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48743051/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com