0

I've encountered a weird behavior that I don't quite get. For the model

class Tenant:
    name = models.CharField(max_length=155)
    country = models.CharField(max_lengh=155)

I'm using this serializer:

class Serializer(serializers.ModelSerializer):
    class Meta:
        model = Tenant
        fields = (name,)

This set up will allow me to save a tenant instance that doesn't have a country supplied even though the null=True should be enforced on the DB level (Postgres). Only when I add country to the fields, will it enforce the null=False constraint.

This seems quite unintuitive to me.


Edit: Here is a simple code example of my problem:

class AppModel(models.Model):
    name = models.CharField(max_length=255)
    country = models.CharField(max_length=255)

class CrateAppModel(APIView):

    def post(self, request, format=None):
        serializer = AppModelSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class AppModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = AppModel
        fields = (
            "name",
        )

Using simple post requests I'm able to create an instance without a country field. I don't understand why? In my database country is of type string and empty.

Xen_mar
  • 8,330
  • 11
  • 51
  • 74
  • In this setup, DRF won't raise any ***validation*** error, but upon calling the `save()` method of serializer, PostgreSQL will raise an error, and so Django too – JPG Oct 23 '20 at 11:33
  • For my use-case it really doesn't. Something internal is populating the field with an empty string. This is really worrisome for me. But there is nothing in my code to explain this. – Xen_mar Oct 23 '20 at 11:48
  • I couldn't reproduce the issue by using ***exact same setup***, Would you mind adding a ***minimal reproducible example***? – JPG Oct 23 '20 at 11:58
  • 1
    Ok, I just build a small example with a standard app. This seems to be the standard behavior for Django. I will add the code – Xen_mar Oct 23 '20 at 12:03
  • I've added the example. – Xen_mar Oct 23 '20 at 12:07
  • 2
    Does this answer your question? [Django Charfield null=False Integrity Error not raised](https://stackoverflow.com/questions/39176618/django-charfield-null-false-integrity-error-not-raised) – JPG Oct 23 '20 at 12:15
  • Yes, it does. Thanks! – Xen_mar Oct 23 '20 at 12:20

0 Answers0