flask-restplus - model inheritance and json fields order

950 Views Asked by At

I have defined 2 models in my flask-restplus app.

some_model = ns.model('SomeModel', {
    'a': fields.String,
    'b': fields.String,
    'c': fields.String
})

some_model_expanded = ns.inherit('SomeModelExpanded', some_model, {
    'd': fields.String,
    'e': fields.String,
})

Now when marshaling an API response with some_model_expanded, I got this in JSON format

{
    "d": "...",
    "e": "...",
    "a": "...",
    "b": "...",
    "c": "..."
}

Is it possible to reorder the fields like this?

{
    "a": "...",
    "b": "...",
    "c": "...",
    "d": "...",
    "e": "...",
}
2

There are 2 best solutions below

0
On

You will find your answer here. But in short:

Both Python dict (before Python 3.7) and JSON object are unordered collections.

There is workarounds to order them, but I dont think it s a good idea to rely on the order of items in a JSON object.

0
On

Yeah. You can use Ordered Dictionary while defining your model.

some_model = ns.model('SomeModel', 
    OrderedDict(
    'a': fields.String,
    'b': fields.String,
    'c': fields.String
    ))