Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correct way to get tag name in xml_field_serializer #248

Open
eltoder opened this issue Mar 25, 2025 · 2 comments
Open

Correct way to get tag name in xml_field_serializer #248

eltoder opened this issue Mar 25, 2025 · 2 comments
Labels
question Further information is requested

Comments

@eltoder
Copy link
Contributor

eltoder commented Mar 25, 2025

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?

@dapper91 dapper91 added the question Further information is requested label Mar 29, 2025
@dapper91
Copy link
Owner

dapper91 commented Mar 29, 2025

@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

@eltoder
Copy link
Contributor Author

eltoder commented Mar 30, 2025

Thanks! This works, but mypy complains:

t.py:10: error: "FieldInfo" has no attribute "path"  [attr-defined]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants