简体   繁体   中英

Django REST Framework's APIClient sends None as 'None'

In my tests, I send mock data of models that I've passed through the serializer. The serializer.data looks something like this

{
    "field": None
}

However, the data that my API receives is formatted like

{
    "field": "None"
}

which is a problem because I'm trying to specify a foreign key that is allowed to be null. Shouldn't the APIClient convert None into null instead of unicode?

Is there any way to fix this or get around it?

Here's my serializer

class MyModelSerializer(serializers.ModelSerializer):

    field = serializers.PrimaryKeyRelatedField(
        queryset=OtherModel.objects.all(), required=False, allow_null=True)

And my create method in a viewset

def create(self, request):
    model = MyModel()
    serializer = MyModelSerializer(model, data=request.data)
    if serializer.is_valid():
        serializer.save(owner=request.user)
        return Response(serializer.data, status=201)
    return Response(serializer.errors, status=406)

Also my model class

class MyModel(models.Model):
    field= models.OneToOneField(
        OtherModel, blank=True, null=True)

The problem here is that the APIClient is sending data to the view as form-data by default, which doesn't have a concept of None or null , so it is converted to the unicode string None .

The good news is that Django REST framework will coerce a blank string to None for relational fields for this very reason. Alternatively, you can use JSON and actually send None or null , which should work without issues.

In addition to what Kevin already said, you can force the APIClient to send JSON using the parameter format='json' .

See the documentation .

In addition to existing answers, if you are expecting a null, this probably means you expect your api to receive json.

If that's the case, you may want to configure the test request default format to json instead of form-data:

In your setting.py:

REST_FRAMEWORK = {
    ...
    'TEST_REQUEST_DEFAULT_FORMAT': 'json'
}

This way, no need to add format='json' to each request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM