Reputation: 4019
I have a Django model that has two required fields - name and a slug. The slug could be passed in during the POST request or otherwise can be generated from name. I then have a model Serializer with both slug and name fields. If the slug is not passed in it throws an error that slug is a required field. However, I want to make it so that if slug is not passed in, I generate it from the name that is always passed in. Is there a way to do this gracefully in Serializer?
Upvotes: 0
Views: 389
Reputation: 634
Try this: add required=False
to the slug
serializer field and then in your serializer's create
method default the slug field to the generated value, like so:
class MyModelSerializer(serializers.Serializer):
slug = serializers.SlugField(required=False)
class Meta:
model = MyModel
def create(self, data):
if not data.get('slug'):
data['slug'] = generate_slug_from_name(data.get('name'))
return super(MyModelSerializer, self).create(data)
Upvotes: 1