vitalik / django-ninja

💨 Fast, Async-ready, Openapi, type hints based framework for building APIs
https://django-ninja.dev
MIT License
6.94k stars 420 forks source link

Field order issue in JSON response #1107

Open Zerotask opened 6 months ago

Zerotask commented 6 months ago

I noticed, that in the JSON response, the fields measurements and units are shown first, before the id, which looks weird. I thought the order is defined in meta fields. Is this a bug or how can I enforce the order from meta fields?

class FieldTypeSchema(ModelSchema):
    measurements: list[MeasurementTypeSchema]
    units: list[UnitSchema]

    class Meta:
        model = FieldType
        fields = (
            "id",
            "key",
            *FieldType.name.fields,
            *FieldType.reference_url.fields,
            "image",
            "data_type",
            "units",
            "min_value",
            "max_value",
            "measurements",
            "attachment",
            "is_commentable",
            "related_field",
            "calculator",
        )
"field_types": [
        {
          "measurements": [],
          "units": [
            {
              "id": 18,
              "key": "quantity",
              "name_en": "...",
              "name_de": "...",
              "name_fr": "...",
              "name_es": "...",
              "name_it": "...",
            }
          ],
          "id": 274,
          "key": "...",
          "name_en": "...",
          "name_de": "...",
          "name_fr": "...",
          "name_es": "...",
          "name_it": "...",
          "reference_url_en": "",
          "reference_url_de": "",
          "reference_url_fr": "",
          "reference_url_es": "",
          "reference_url_it": "",
          "image": "",
          "data_type": "integer",
          "min_value": "",
          "max_value": "",
          "attachment": "optional",
          "is_commentable": true,
          "related_field": null,
          "calculator": null
        },
        ...
]
vitalik commented 6 months ago

Hi @Zerotask

well this happens somewhere inside pydantic - django ninja sends fields definitions as dict (where fields are sorted as in Meta.fields) but apparently pydantic puts attributes defined on class first

I think I raised this at pydantic issues once but did not get a solution..