Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django primarykey serializer "This field may not be null" while allow_null=True

I've been struggling with this problem.

I am not sure what I'm missing.

Please let me know if you have any suggestions..!!

models.py:

co_manager = models.ManyToManyField(BookRunner, blank=True, null=True, related_name="deal_co_manager")

views.py:

 class DealAdminViewSet(viewsets.ModelViewSet):
      queryset = Deal.objects.all()
      serializer_class = CreateDealSerializer

      def create(self, request, format=None):
          data = ...all things data here.
          serializer = CreateDealSerializer(data=deal)
          print serializer
          co_manager_array = []
          if serializer.is_valid():
              serializer.save()
              return Response(status=status.HTTP_201_CREATED)
          else:
              return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializer.py:

class CreateDealSerializer(serializers.Serializer):
    co_manager = serializers.PrimaryKeyRelatedField(allow_null=True, many=True, queryset=BookRunner.objects.all(), required=False)
like image 594
Henry H Avatar asked Jun 02 '17 06:06

Henry H


People also ask

What does this field may not be null mean?

A “NOT NULL constraint” enforces that a database column does not accept null values. Null, according to Wikipedia, is. a special marker used in Structured Query Language (SQL) to indicate that a data value does not exist in the database.

What is serializer method field in Django?

Each field in a Form class is responsible not only for validating data, but also for "cleaning" it — normalizing it to a consistent format. — Django documentation. Serializer fields handle converting between primitive values and internal datatypes.

Is serializer necessary in Django?

It is not necessary to use a serializer.

What does serializer save do in Django?

Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. The serializers in REST framework work very similarly to Django's Form and ModelForm classes.


2 Answers

I would suggest editing your views, more like this,

class DealAdminViewSet(viewsets.ModelViewSet):
  queryset = Deal.objects.all()
  serializer_class = CreateDealSerializer

  def create(self, request, *args, **kwargs):
      serializer = self.get_serializer(data=request.data)
      if serializer.is_valid():
          serializer.save()
          return Response(serializer.data, status=status.HTTP_201_CREATED)
      return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Without showing your models, the help anyone could offer is pretty much limited. Please let me know, if anything comes up.

Also, your serializers,

class CreateDealSerializer(serializers.Serializer):
    co_manager = serializers.PrimaryKeyRelatedField(allow_null=True, many=True, queryset=BookRunner.objects.all())

The error is triggering because, in your models the field co_manager is not defined as null=True. If you want to save the above field as null, then change in your models.py,

co_manager = models.ForeignKey(Target_table_name, null=True, blank=True)

The error won't be raised, when null value is stored.

like image 166
zaidfazil Avatar answered Oct 19 '22 19:10

zaidfazil


Just send an empty list if serializer is set with many = True, allow_null=True

from serliazer:

many_field = serializers.PrimaryKeyRelatedField(queryset=qs, read_only=False, many=True, allow_null=True)

class Meta:
    model = ModelName
    fields = (
        'many_field ',
         ...)
    extra_kwargs = {
        'many_field': {'required': False},
    }

and in the requests data:

 data = {'NOT_many_field': None,
 'many_field': []}
like image 23
Ohad the Lad Avatar answered Oct 19 '22 19:10

Ohad the Lad