0

I currently have 2 models which are related by a 1:1 relationship which will always be displayed together. The models are linked via a common PK. I have created the two models which map to their tables using flask-sqlalchemy. I will make a simplified version below:

class Author(db.Model):
    key = db.Column(db.Text)
    name = db.Column(db.Text)

class Book(db.Model):
    key = db.Column(db.Text)
    title = db.Column(db.Text)

Then I can make my serializes using flask-marshmallow:

class AuthorScheme(ma.SQLAlchemyAutoScheme):
    class Meta:
        model = models.Author

class BookScheme(ma.SQLAlchemyAutoScheme):
        class Meta:
            model = models.Book

This is good for individual schemes, and I know you can use nesting but its not the format I am trying to create. If I put the author nested in the book it produces an output like:

{
    key: value,
    title: value,
    author: {
        key: value,
        name: value
    }
}

I have seen other solutions using model foreign keys which produce similar results to above. However, I am trying to get it to serialize like:

{
    key: value,
    title: value,
    author: value,
}

Where the two models know to merge on 'key' and combine into one. Would this be done in the actual models? Or in the scheme? I am lost. I also recognize you can do this manually and set the field but I would like to find a better approach since I will be doing a get all endpoint and would prefer to not iterate on all models. Any Ideas?

Scott Glascott
  • 537
  • 1
  • 5
  • 15

1 Answers1

1

If you are using Marshmallow V3 you can use the Pluck field (docs here). Something like the following (not tested):

class AuthorScheme(ma.SQLAlchemyAutoScheme):
    class Meta:
        model = models.Author

class BookScheme(ma.SQLAlchemyAutoScheme):
    class Meta:
        model = models.Book

    author = fields.Pluck(AuthorSchema, 'name')

This should serialize to:

{
    key: value,
    title: value,
    author: value,
}
pjcunningham
  • 7,676
  • 1
  • 36
  • 49