yezyilomo / django-restql

Turn your API made with Django REST Framework(DRF) into a GraphQL like API.
https://yezyilomo.github.io/django-restql
MIT License
616 stars 43 forks source link

Constraint error after a validation from model #215

Closed alepn closed 3 years ago

alepn commented 3 years ago

After a validation from model (ex.: unique field violate), I cannot send the request again.

It causes a constraint error:

null value in column "foo_id" violates not-null constraint

yezyilomo commented 3 years ago

It’s hard to know what might be causing that problem if you don’t post a piece of code which you think it might be causing that error, so please do.

alepn commented 3 years ago

MODELS

class Profile(models.Model):
    name = models.CharField('Name', max_length=80)

class Email(models.Model):
    profile = models.ForeignKey(Profile)
    email = models.CharField('Email', max_length=80, unique=True)

SERIALIZERS

from django_restql.mixins import DynamicFieldsMixin
from django_restql.serializers import NestedModelSerializer

class EmailSerializer(DynamicFieldsMixin, NestedModelSerializer):
    class Meta:
        model = Email
        fields = ['profile','email']

class ProfileSerializer(DynamicFieldsMixin, NestedModelSerializer):
    email_set = NestedField(EmailSerializer, many=True, required=False, allow_null=True)
    class Meta:
        model = Email
        fields = ['name','email_set']

If you send a request with a existing email, it will fail because the unique constraint. If you resend the request with another e-mail, it show a fk constraint error, because profile_id on nested email_set was lost. Tested with django-restql versions: 0.10.2 and 0.11.2

yezyilomo commented 3 years ago

This is not django-restql's problem, DRF doesn't handle all IntegrityErrors raised by django ORM due to failed database constrains, so you are supposed to handle these yourself by using fields validation on your serializers, the way you did it here