使用 unique_together 时,drf ModelViewset 不验证唯一约束失败

drf ModelViewset does not validate Unique Constraint failed when unique_together is used

我正在使用 djangorestframework==3.12.1 我的代码如下所示:-

models.py

class Product(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=14, decimal_places=2)
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.name

    class Meta:
        unique_together = (
            ("name", "user"),
        )

serializers.py

class ProductSerializer(serializers.ModelSerializer):
    """serializer for Product objects."""

    class Meta:
        model = models.Product
        fields = '__all__'
        read_only_fields = ['user',]

views.py

class ProductViewset(viewsets.ModelViewSet):
    queryset = models.Product.objects.all()
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = serializers.ProductSerializer

预期行为

Modelserializers 上的验证器必须引发异常 Product with this Name and User already exists.

实际行为

IntegrityError at /api/v1/product/ UNIQUE constraint failed: projectapp_product.name, projectapp_product.user_id

我该如何解决这个问题?

您可以尝试覆盖 ProductViewSet 的 perform_create 像这样:

class ProductViewset(viewsets.ModelViewSet):
    queryset = models.Product.objects.all()
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = serializers.ProductSerializer

    def perform_create(self, serializer):
        user = self.request.user
        try:
            serializer.save(user=user)
        except IntegrityError:
            raise ValidationError('Product with this Name and User already exists.')