Home > Enterprise >  Cannot use serializer when ManyToManyField is empty
Cannot use serializer when ManyToManyField is empty

Time:11-21

I am utilizing PrimaryKeyRelatedField to retrieve and write M2M data.

My models.py:

class Task(MP_Node):
    ...
    linked_messages = models.ManyToManyField('workdesk.Message', blank=True, related_name='supported_tasks')

(MP_Node is an abstraction of models.Model from django-treebeard).

My serializers.py:

class TaskSerializer(serializers.ModelSerializer):
    ...
    linked_messages = serializers.PrimaryKeyRelatedField(many=True, required=False, allow_null=True, queryset=Message.objects.all())

    class Meta:
        model = Task
        fields = [..., 'linked_messages']

My api.py:

class TaskViewSet(ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

def create(self, request):
    serializer = self.get_serializer(data=request.data)
    if serializer.is_valid(raise_exception=True):
        print(serializer.data)

With other fields, if the field is set to null=True in the models, or required=False on the serializer, I don't need to include them in the data to instantiate the serializer. However, these fields do not seem to work this way, instead returning KeyError: 'linked_messages' when serializer.data is called.

As a workaround I tried adding setting allow_null, as indicated by the docs, and then manually feed it a null value:

request.data['linked_messages'] = None

but this returns as 404:

"linked_messages":["This field may not be null."]

If I set it to a blank string:

"resources":["Expected a list of items but got type \"str\"."]

If I set it to an empty list, serializer.data again gives me an error:

`TypeError: unhashable type: 'list'`

It seems to have me any way I turn. What am I not understanding about this field?

CodePudding user response:

Use default argument -

linked_messages = serializers.PrimaryKeyRelatedField(
    many=True,
    queryset=Message.objects.all(),
    default=[]
)

# print(serializer.data)
# {'linked_messages': []}
  • Related