BeanieODM / beanie

Asynchronous Python ODM for MongoDB
http://beanie-odm.dev/
Apache License 2.0
2.05k stars 217 forks source link

[BUG] Beanie does not properly supports pydantic.AliasGenerator #1033

Open jcierocki opened 1 month ago

jcierocki commented 1 month ago

Describe the bug I receive data with all field names following camel case and I need this data immediately inserted into the database, without any additional processing. But I prefer to keep all the field names in the database in snake case. Pydantic V2 allows to specify different aliases for validation and serialisation using pydantic.AliasGenerator but Beanie does support this at all, leading to unexpected behaviour. In make case this issue is primarily inserting Document.id as "id" not "_id".

Providing AliasGenerator as an argument to ConfigDict affects the behaviour of Document.model_fields. That is the instances of FieldInfo class no longer have attribute alias but validation_alias (if provided) and seralization_alias (if provided). After digging a little bit into Beanie code I believe I found at leat the partial source of this issue here: link. beanie.odm.utils.Encoder._iter_model_items() recognises neither FieldInfo.validation_alias nor FieldInfor. seralization_alias.

To Reproduce

from beanie import Document
from beanie.odm.documents import document_alias_generator
from pydantic import ConfigDict, AliasGenerator
from pydantic.alias_generators import to_camel

class SomeBeanieModel(Document):
    model_config = ConfigDict(alias_generator=AliasGenerator(validation_alias=lambda s: document_alias_generator(to_camel(s)), seralization_alias=document_alias_generator)

    some_field: int

SomeBeanieModel(some_field=1).insert()

Expected behavior I believe Beanie should support serialization_alias while loading to/from database. That is, if serialization_alias is provided, it is responsible for mapping MongoDB field names and Python ODM model attributes. If not provided, the default alias generator, that is document_alias_generator (using Python field names with an exception for id mapped as _id) should be used.For constructing Document instances in Python, both the real field names and the aliases defined by validation_alias should be supported, with either error on collision or the conversion controlled by pydantic.fields.FieldInfo.alias_priority.

github-actions[bot] commented 8 hours ago

This issue is stale because it has been open 30 days with no activity.