Best way for update object with Nested schema

Viewed 911

I have two model: ArticleModel and TagModel and May-To-Many relation between them. I'm use marshmallow for [de]serializtion.

I want update or create ArticleModel instance and I want get from front-end following data

{
  'title': 'article',
  'tags': [1, 2, 4] // ids of TagModel instances
}

I desided it

schemas

class ArticlePutPostSchema(Schema):
    tags = fields.List(fields.String())

view

def post(self):
    json_data = request.get_json()
    data = ArticlePutPostSchema().load(data=json_data, partial=True)
    data["tags"] = list(
        TagModel.query.filter(TagModel.id.in_(data["tags"]))
    )
    article = ArticleModel(**data)
    db.session.add(article)
    db.session.commit()
    return jsonify(), 200

But I think, that its bad way.

Also I tried to apply a Pluck field

Pluck(TagSchema, 'id', many=True)

And I got [{'id': 1, 'id': 2, 'id': 4}].

It's also a bad way.

How can to solve it?

1 Answers

A good way to do this is to define a nested schema in ArticlePutPostSchema as described here.

class TagModelSchema(Schema):
    id = fields.Integer()
    name = fields.String()

class ArticlePutPostSchema(Schema):
    tags = fields.List(fields.Nested(TagModelSchema))

With the nested schema your data['tags'] should look like this:

[{id: 1, name: 'foo'}, {id: 2, name: 'bar'}, ... ]

So you don't have to query TagModel anymore.

Maybe you have to refactor your ArticleModel an TagModel for this to work as expected. I.e. you need a db.relationship() between the two classes.

Related