alias_generator not working if there are extra (non-alias) fields #645
Closed
Description
Bug
Depending on your point of view this might not be a bug but it would be cool to address in any case.
For my models I have special field configurations that I add to the Config.fields
. I recently tried the alias_generator
option on the Config to force fields to camel case. The problem is when Config.get_field_schema
runs it thinks there is a field config so it skips the alias_generator.
It makes sense to skip it if there is an alias
but in my case there are other field options but not an alias.
For bugs/questions:
- OS: OSX
- Python version
import sys; print(sys.version)
: 3.7.3 - Pydantic version
import pydantic; print(pydantic.VERSION)
: 0.30.0
Where possible please include a self contained code snippet describing your
bug, question, or where applicable feature request:
import pydantic
import stringcase
Person(BaseModel)
first_name: str
last_name: str
class Config:
alias_generator = stringcase.camelcase
fields = {
"first_name": { "myCustomOp": True }
}
person = Person(first_name="Arthur" last_name="Dent")
d = person.dict(by_alias=True)
# {"first_name": "Arthur", "lastName": "Dent"}
Proposed Solution
Run the generator if it is present and 'alias' is not present.
How does this look for a fix?
@classmethod
def get_field_schema(cls, name: str) -> Dict[str, str]:
field_config = cls.fields.get(name) or {}
if isinstance(field_config, str):
field_config = {'alias': field_config}
elif cls.alias_generator:
if not field_config or 'alias' not in field_config:
alias = cls.alias_generator(name)
if not isinstance(alias, str):
raise TypeError(f'Config.alias_generator must return str, not {type(alias)}')
if not field_config:
field_config = {}
field_config['alias'] = alias
return field_config