P
P
Philip Bondarev2018-11-19 15:10:46
ORM
Philip Bondarev, 2018-11-19 15:10:46

What is the proper way to serialize nested Flask-SQLAlchemy objects using Flask-Marshmallow?

Good afternoon.
There are two tables:

Organizations
class Organization(mixins.PaginatedAPIMixin, db.Model):
    __tablename__ = 'organization'

    id = db.Column(db.Integer, primary_key=True, nullable=False, unique=True)
    name = db.Column(db.String(128), nullable=False)
    document_cipher = db.Column(db.String(6), unique=True)
    address = db.Column(db.String(256))
    website = db.Column(db.String(32))
    is_active = db.Column(db.Boolean, default=True)
    organization_type_id = db.Column(db.ForeignKey('organization_type.id'),
                                     nullable=False, index=True)
    organization_type = db.relationship('OrganizationType', backref='organizations', lazy=True)
and
Organization types
class OrganizationType(mixins.PaginatedAPIMixin, db.Model):
    __tablename__ = 'organization_type'

    id = db.Column(db.Integer, primary_key=True, unique=True)
    type = db.Column(db.String(45), nullable=False, unique=True)
    description = db.Column(db.Text)
Also, there are schemes for their (de)serialization:
Organization Chart
class OrganizationsSchema(ma.ModelSchema):
    class Meta:
        model = Organization
and
Organization Type Schema
class OrganizationsTypesSchema(ma.ModelSchema):
    class Meta:
        model = OrganizationType

In the end, I want to get this:
serialized object
{
  "_links": {},
  "_meta": {},
  "items": [
    {
      "address": "address",
      "document_cipher": "ABCD",
      "id": 1,
      "name": "ООО \"Horns'n'Hoofs\"",
      "organization_type": {
            "id": 1,
            "name": "Owner",
            "description": "spam"
            },
      "website": "http://hnh.ololo"
    }
  ]
}

(I put an array in organization_type to unify the output, there will be many sub-objects in some places), but at the moment, with the code above, I have just a property ID in organization_type ... How to deal with this?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question