![]() So something like this (Note that I did not fully test the code below but it should be something along these lines): class PostSerializer(serializers.ModelSerializer):Ĭountry = serializers. See the documentation here for more information on specifying or overriding fields explicitily: This article supposes you already have a fair understanding of Django REST Framework. ![]() Along the way, we'll dive into some advanced concepts like using the source keyword, passing context, validating data, and much more. If you are using pre-DRF 3.2.4, then you can override the field in the serializer and add required=False to it. In this article, we'll look at how to use Django REST Framework (DRF) serializers more efficiently and effectively by example. See the answer here for more information: DjangoRestFramework - correct way to add "required = false" to a ModelSerializer field? Then DRF will treat the field as optional when serializing and deserializing it (Note though that if there is no null=True on the model field, then Django will raise an error if you try to save an object to the database without providing the field). To the models field like so: class Post(models.Model):Ĭountry = models.ForeignKey(Country, blank=True) I basically want to omit the field (or at least make the value None) when serializing an object If the field is null.Īs of DRF 3.2.4, so long as you add blank=True ![]() I don't think I can use SerializerMethodField ( ) because the 'country' field is not a read-only field (I write too it too, if it is provided). Is there any way for me to tell DRF that if the value of the field is null (because the 'country' field is optional and sometimes not provided) then to skip it and just serialize the other data? Or at least serialize it with a value of None? This is my Model: class Post(models.Model):Ĭountry = models.ForeignKey(Country, blank=True, null=True)Īnd this is my serializer: class PostSerializer(serializers.ModelSerializer):
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |