简体   繁体   中英

How to make ListField in ModelSerializer DRF not mandatory

I want a field in my Django model that stores a list of strings (I don't want to use a related field for some reasons, only validate that user has sent a correct list).

I have it correctly working, the problem is that I'm not success to make this field not mandatory when updating the object via Django REST Framework.

This is my implementation, I have test some variations with the same result

class SomeModel(models.Model):
    hashtags = models.CharField(max_length=512, default=None, null=True, blank=True)

    @property
    def hashtags_as_list(self):
        """ Hashtags are stored on DB as a text json convert to object again
        """
        return json.loads(self.hashtags) if self.hashtags else None

    @hashtags_as_list.setter
    def hashtags_as_list(self, value):
        """ Hashtags are stored on DB as a text json of the list object
        """
        self.hashtags = json.dumps(value)

class SomeModelSerializer(serializers.ModelSerializer):
    hashtags = serializers.ListField(
        source='hashtags_as_list',
        default = [],
        required = False,
        child = serializers.CharField(min_length=3, max_length=32, required=False)
    )

I only get the error when I do PUT on the Browsable API, inspecting the query is sending hashtags blank.

------WebKitFormBoundary4L5MFBPrRA0QDqFL
Content-Disposition: form-data; name="hashtags"


------WebKitFormBoundary4L5MFBPrRA0QDqFL

And the error is as follows:

{
    "hashtags": [
        "This field may not be blank."
    ]
}

You are sending post data for hashtags except without content which is why DRF is returning that error message. You can fix that by using:

hashtags = serializers.ListField(required=False, child=CharField(allow_blank=True, ...), ...)

Please note however that you might need to adjust some of your code to handle when hashtags will normalize to empty string.

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