Home > Back-end >  How to get auto fill values(default values) on serializer create method in django?
How to get auto fill values(default values) on serializer create method in django?

Time:08-06

I have a model like this:

class Post(BaseModel):
        post_user_id = models.CharField(max_length=500, unique=True, default=create_uid)

create_uid gerenrates a unique id

serializer:

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'

    def create(self, validated_data):
        print(validated_data['post_user_id'])
        return super().create(validated_data)

For each created post a post_user_id will be generated automatically and the user will not post the post_user_id On print(validated_data['post_user_id']) I want to print the generate number But I get error

KeyError

CodePudding user response:

Default values gets assigned when the instance is created. You are trying to print before that. If you want to get the id in craete function ,you can print after calling the super.create() . Do not forget to return the object later.

def create(self, validated_data):
    obj=  super().create(validated_data)
    print(obj.post_user_id)
    return obj 
  • Related