DRF Serializer, A field that accept both Integers and Null.

Hi, I’ve got a model looks like this.

car = models.ForeignKey(Car, related_name='owner_profile', blank=True, null=True, on_delete=models.SET_NULL)

And I’ve got a serializer for this model.

...
...
car = serializers.IntegerField(requied=False, allow_null=True)

I want the serializer field to accept both integer and null.

How should I do that?

I am using Swagger UI to test APIs and I cannot input null for the field.

Thanks in advance

PS: Finally, I want to set set that ForeignKey to existing object or None.

Hi,

Can you please explain a bit more about what it is you want to do? For example, I have a generics.CreateAPIView which uses a ModelSerializer for this model and I want to be able to do x.

And please tell us what it is that is not working for you.

Hi, @conor

Thank you for your attention.
So yes, I have a ModelSerializer for the model and as you can see the field can be set to None as it has null=True.

And I am using GenericViewSet patch method to update the model.

I am testing on Swagger UI to set that field to None by passing null to that field but it is not working.
The API request is not sent since the validation of that field does not allow null.
Hope this explains

Is it the swagger UI that is not allowing the null field, or is it your endpoint? You can check your endpoint using a different tool such as curl. If the endpoint works and it’s just the UI failing, this may be a swagger issue.

1 Like

Have you tried navigating to the endpoint in your browser and using the DRF GUI to test if you can send a null value? If that works then this might be a specific problem to the Swagger generator you are using.

I have several serializers where I use required=False and allow_null=True and they work fine.

1 Like

Oh, no, I mislooked, it’s not working

Can you please provide the error, the exception and the relevant code. It’s impossible to help without it.

Actually, I need to have two fields one boolean flag to enable/disable a feature and a foreign key to another model.
But i thought setting the foreign key field to null will disable the feature, so I was trying to add only a single field instead of two.
Now I rolled back and added two fields which made it easier.
Thank you for your attention

Hi @devspectre,
Have seen that you have a typo in your serializer ?

car = serializers.IntegerField(requied=False, allow_null=True)

Try with 'required=False' instead of 'requied=False'.