Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pydantic exclude multiple fields from model

In pydantic is there a cleaner way to exclude multiple fields from the model, something like:


class User(UserBase):
    class Config:        
        exclude = ['user_id', 'some_other_field']

I am aware that following works.


class User(UserBase):

    class Config:       
        fields = {'user_id': {'exclude':True}, 
                   'some_other_field': {'exclude':True}
                 }

but I was looking for something cleaner like django rest framework, where you could just specify a list of exclude or include per.

like image 884
muon Avatar asked Sep 02 '25 16:09

muon


1 Answers

Pydantic will exclude the class variables which begin with an underscore. so if it fits your use case, you can rename your attribues.

class User(UserBase):
    _user_id=str
    some_other_field=str
    ....
like image 146
N.Moudgil Avatar answered Sep 05 '25 10:09

N.Moudgil