Use UniqueTogetherValidator instead of custom validate function

This commit is contained in:
Chandrapal Badshah committed 2025-05-14 14:45:25 +05:30
1 parent 461eb7ab85
commit b147e1056c
2 files changed
+9 -19

No files matched your search

+2 -10
View File
@@ -5485,16 +5485,8 @@ class TestLighthouseConfigViewSet:
assert any(field in error["source"]["pointer"] for error in errors)
def test_lighthouse_config_create_duplicate(
self, authenticated_client, valid_config_payload
self, authenticated_client, valid_config_payload, lighthouse_config_fixture
):
# Create first config
response = authenticated_client.post(
reverse("lighthouseconfig-list"),
data=valid_config_payload,
content_type=API_JSON_CONTENT_TYPE,
)
assert response.status_code == status.HTTP_201_CREATED
# Try to create second config for same tenant
response = authenticated_client.post(
reverse("lighthouseconfig-list"),
@@ -5503,7 +5495,7 @@ class TestLighthouseConfigViewSet:
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert (
"AI configuration already exists for this tenant"
"Lighthouse configuration already exists for this tenant"
in response.json()["errors"][0]["detail"]
)
+7 -9
View File
@@ -7,6 +7,7 @@ from django.contrib.auth.models import update_last_login
from django.contrib.auth.password_validation import validate_password
from drf_spectacular.utils import extend_schema_field
from jwt.exceptions import InvalidKeyError
from rest_framework.validators import UniqueTogetherValidator
from rest_framework_json_api import serializers
from rest_framework_json_api.serializers import ValidationError
from rest_framework_simplejwt.exceptions import TokenError
@@ -2181,16 +2182,13 @@ class LighthouseConfigCreateSerializer(RLSSerializer, BaseWriteSerializer):
"business_context",
"is_active",
]
def validate(self, attrs):
tenant_id = self.context.get("request").tenant_id
if LighthouseConfig.objects.filter(tenant_id=tenant_id).exists():
raise serializers.ValidationError(
{
"tenant_id": "AI configuration already exists for this tenant. Use PUT to update."
}
validators = [
UniqueTogetherValidator(
queryset=LighthouseConfig.objects.all(),
fields=["name"],
message="Lighthouse configuration already exists for this tenant.",
)
return super().validate(attrs)
]
def create(self, validated_data):
api_key = validated_data.pop("api_key")