pydantic-xml
pydantic-xml copied to clipboard
Correct way to get tag name in xml_field_serializer
In the code below I'm writing a custom serializer for list[int] fields. In the serializer I need to know the tag name of the field, rather than the field name. These are not the same because tag names contain dashes (-), so I had to rename them:
import pydantic_xml as pxml
class Model(pxml.BaseXmlModel):
x_ids: list[int] = pxml.element(tag="x-ids")
y_ids: list[int] = pxml.element(tag="y-ids")
@pxml.xml_field_serializer("x_ids", "y_ids")
def _serialize_ids(self, elem, value, field):
# need the tag name ("x-ids" or "y-ids") here
What is the recommended way to get the tag name?
@eltoder Hi,
Tag name is not passed to the serializer directly, but you are able to extract it from the model field metadata:
import pydantic_xml as pxml
class Model(pxml.BaseXmlModel):
x_ids: list[int] = pxml.element(tag="x-ids")
y_ids: list[int] = pxml.element(tag="y-ids")
@pxml.xml_field_serializer("x_ids", "y_ids")
def _serialize_ids(self, elem, value, field):
tag_name = self.model_fields[field].path
Thanks! This works, but mypy complains:
t.py:10: error: "FieldInfo" has no attribute "path" [attr-defined]
You may check the field_info type before:
@pxml.xml_field_serializer("x_ids", "y_ids")
def _serialize_ids(self, elem, value, field):
if isinstance(field_info := self.model_fields[field], pxml.fields.XmlEntityInfo):
tag_name = self.model_fields[field].path
else:
...