L. Quastana
L. Quastana

Reputation: 1336

Flask sql alchemy get child object

When I declare a relationship with SQL-Alchemy, I don't found all the child's data when Marshmallow dumps the object. When Marshmallow deserialize the object, i would like to get my Member object to json not just the Ids.

My models :

class Company(db.Model):
    __table_args__ = {"schema": "public"}
    id_company = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    members = db.relationship('Member', back_populates="company", lazy='joined')

class Member(db.Model):
    __table_args__ = {"schema": "public"}
    id_member = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120), nullable=False)
    age = db.Column(db.Integer)
    company_id = db.Column(db.Integer, db.ForeignKey('public.company.id_company'), nullable=False)
    company = db.relationship("Company", back_populates="members",lazy='joined')

class MemberSchema(ma.ModelSchema):
    class Meta:
        model = Member


class CompanySchema(ma.ModelSchema):
    class Meta:
        model = Company

class CompanyIdInputSchema(Schema):
    id_company = fields.Integer(required=True)

My route :

company_schema = CompanySchema()
pagination_schema = PaginationInputSchema()
company_id_schema = CompanyIdInputSchema()

class CompanyById(Resource):
    @swag_from('swag_docs/swag_company_get.yml')
    def get(self, id_company):
        company_id_args = {"id_company": id_company}
        errors = company_id_schema.validate(company_id_args)
        if errors:
            return {"error": str(errors)}, 500
        else:
            company = Company.query.filter_by(id_company=id_company)
            company = companies_schema.dump(company)
            if len(company)>=1:
                return company, 201
            else:
                return 204

The result when a call the route is :

  {
    "members": [
      1
    ],
    "id_company": 1,
    "name": "Total"
  }

What i expect :

  {
    "members": [
      {'id_member':1,'name':'Laurent','age':32,'company_id'=1}
    ],
    "id_company": 1,
    "name": "Total"
  }

Upvotes: 0

Views: 305

Answers (1)

stasiekz
stasiekz

Reputation: 1863

If you want the serializer to serialize nested field as a list of serialized objects instead of ids you need to add Nested field with many=True.

class CompanySchema(ma.ModelSchema):
    members = ma.fields.Nested(MemberSchema, many=True)
    class Meta:
        model = Company

Upvotes: 2

Related Questions