Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAthanor: serialize to json only specific fields

Is there a way to serialize a SQLAlchemy model including only specific fields using SQLAthanor? The documentation doesn't mention it, so the only way that I figured out is to filter the outcome manually.

So, this line with sqlathanor

return jsonify([user.to_dict() for user in users for k, v in user.to_dict().items() 
                                if k in ['username', 'name', 'surname', 'email']])

is equivalent to this one using Marshmallow

return jsonify(SchemaUser(only=('username', 'name', 'surname', 'email')).dump(users, many=True))

Once again, is there a built-in method in SQLAthanor to do this?

like image 605
Aleksandra Rievva Avatar asked Feb 25 '26 17:02

Aleksandra Rievva


1 Answers

Adapting my answer from the related Github issue:

The only way that you can change the list of serialized fields without adjusting the instance’s configuration is to manually adjust the results of to_<FORMAT>(). Your code snippet is one way to do that, although for JSON and YAML you can also supply a custom serialize_function which accepts the dict, processes it, and serializes to JSON or YAML as appropriate:

import simplejson as json

def my_custom_serializer(value, **kwargs):
    filtered_dict = {}
    filtered_dict['username'] = value['username']
    # repeat pattern for other fields

    return json.dumps(filtered_dict)

json_result = user.to_json(serialize_function = my_custom_serializer)`

Both approaches are effectively the same, but the serialize_function approach gives you more flexibility for more complex adjustments to your serialized output and (I think) easier to read/maintain code (though if all your doing is adjusting the fields included, your snippet is already quite readable).

You can generalize the serialize_function as well. So if you want to give it a list of fields to include, just include them as a keyword argument in to_json():

def my_custom_serializer(value, **kwargs):
    filter_fields = kwargs.pop(“filter_fields”, None)
    result = {}
    for field in filter_fields:
        result[field] = value.get(field, None)

    return json.dumps(result)

result = [x.to_json(serialize_funcion = my_custom_serializer,  filter_fields = ['username', 'name', 'surname', 'email']) for x in users)
like image 179
Chris Modzelewski Avatar answered Feb 27 '26 07:02

Chris Modzelewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!