I have a table called Type that associates with a table called Language. I have a 1to1 and a 1tomany relatioship for language and translated_languages from Type to Language. When I try to pull the language out of the 1toMany relationship it gives me the objective reference.
Here is my schema setup
class TypeSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Type
include_relationships = True
#This works great!
language = ma.String(attribute="language.language", dump_only=True)
#This gives me an object reference
translated_languages = ma.List(ma.String(attribute="language.language", dump_only=True))
Here is the output JSON language shows properly, but the translated languages fail for some reason.
{
"language": "en",
"translated_languages": [
"<api.models.Language object at 0x000002598642C8E0>",
"<api.models.Language object at 0x000002598642C850>",
"<api.models.Language object at 0x000002598642C970>"
]
}
Here is my route and the model defining the associations
@types.route('/types', methods=['GET'])
@authenticate(token_auth)
@paginated_response(type_schema)
def all():
"""Retrieve all types"""
return Type.select()
class Type(Updateable, db.Model):
__tablename__ = 'type'
translated_languages = sqla_orm.relationship('Language', back_populates='type', foreign_keys='Language.type_id')
language = sqla_orm.relationship('Language', back_populates='types', uselist=False, foreign_keys='Language.types_id')
class Language(Updateable, db.Model):
__tablename__ = 'language'
id = sqla.Column(sqla.Integer, primary_key=True)
language = sqla.Column(sqla.String(2), nullable=False)
type_id = sqla.Column(sqla.Integer, sqla.ForeignKey('type.id'), index=True)
type = sqla_orm.relationship('Type', foreign_keys='Language.type_id', back_populates='translated_languages')
types_id = sqla.Column(sqla.Integer, sqla.ForeignKey('type.id'), index=True)
types = sqla_orm.relationship('Type', foreign_keys='Language.types_id', back_populates='language')
In marshmallow, fields.List will send the inner object to fields.String as value(see marshmallow.fields.List._serialize), while fields.String will simply convert the input value to string(see marshmallow.fields.String._serialize).
This is why your objects in
translated_languagesshown as "<api.models.Language object at 0x000002598642C8E0>".In order to dump as expect, we can use a custom field which is inherited from fields.List and override it's _serialize function.
There is an example for you.
CustomInnerSerializerListFieldis the custom field, and in the dump results theinner_namestoinner_names6are all my failed attempts,inner_names_expectedis the exatily result I want.