Question on ordering of fields #226
-
Just wondering what it is I am doing incorrectly when wanting to order fields: Per the documentation (https://wyfo.github.io/apischema/de_serialization/#class-level-ordering), this works as expected. However, when I try to do the following: @order(["hairColor", "name", "age"])
@dataclass
class Person:
"""Model to represent a person object"""
name: str
age: int
hair_color: str = field(metadata=alias("hairColor"))
person = Person("John", 21, "Brown")
print(json.dumps(serialize(person)))
>>> '{"hairColor": "Brown"}' What I would expect the output to be is as follows: >>> '{"hairColor": "Brown", "name": "John", "age": 33}' Am I doing something wrong? Also, when decorating the class with the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
There are several issue here: a misuse due to an incomplete documentation, a bug, and maybe a feature request. On the one hand, about the documentation; apischema has several features expecting fields as argument, for example fields validator or ordering. This not really documented, but fields can be passed either as a dataclass field (convenient inside class body), On the other hand, there is a bug in the current implementation (i will fix it today and release it in v0.16.1 at the same time). Ordering @dataclass
class Person:
name: str = field(metadata=order(after="hair_color"))
age: int = field(metadata=order(after="name"))
hair_color: str = field(metadata=alias("hairColor")) That's why, even if you fix your decorator to be I will also update the documentation to precise that field aliases cannot be used, for the moment. I understand that it could be convenient to use aliases in addition to field names, and I will think about it. I should not be so hard to do, even if there is some edge cases to handle, but I have other priority things to implement at this moment. By the way, regarding your example, apischema provides dynamic/global aliasing, which is a lot more convenient than aliasing fields one by one, especially for camelCase handling. P.S. Don't hesitate to create issue instead of question when the things looks a lot like a bug (having fields not serialized). I've created #227 |
Beta Was this translation helpful? Give feedback.
There are several issue here: a misuse due to an incomplete documentation, a bug, and maybe a feature request.
On the one hand, about the documentation; apischema has several features expecting fields as argument, for example fields validator or ordering. This not really documented, but fields can be passed either as a dataclass field (convenient inside class body),
apischema.objects.ObjectField
or a string, which is expected to be the field name. Field alias cannot be used here, so your example will not work. You have to replace"hairColor"
by"hair_color"
.On the other hand, there is a bug in the current implementation (i will fix it today and release it in v0.16.1 at the same time). Or…