0

I'm a relatively new python user, coming from the .NET world.

I'm working on a web application with a python backend (using Flask and SQLAlchemy), where the db models are defined using SQLAlchemy and now I'm writing my first function where I want to retrieve data from the database and bring to the frontend.

Here is a non-functional example (since SQLAlchemy cannot be jsonified directly) just to show what I want to do:

@app.route('/validationrules', methods=["GET"])
@login_required
def getValidationRules():

    return jsonify(db.session.query(ValidationRules).all())

My question is, is it customary to create view models when using the stack I mentioned above, and use those to create a bridge between the SQLAlchemy and json? Or do I just create a custom dict in every method and jsonify that?

Some search results also suggested that I create a base model with a to_dict method, and have all my database models inherit from that, but that seems a bit too coupled to me.

What are the best practices for a case like this?

Nanna
  • 515
  • 1
  • 9
  • 25

1 Answers1

0

UPDATE: Following this answer I would now change my answer to use marshmallow / marshmallow-sqlalchemy.

Previous answer:

I don't know the answer for certain but...

From Miguel Grinberg's Flask Web Development 2nd edition, page 210-213 the approach he uses is to have a method

def Post(db.Model):
    # ...
    def to_json(self):
        json_post = {
            ** json using model **
        }
        return json_post

defined in the models.py

Andrew Allen
  • 6,512
  • 5
  • 30
  • 73
  • Take a look at Chapter 14 API(4a) https://github.com/miguelgrinberg/flasky/commits/master – Andrew Allen Mar 05 '19 at 15:21
  • Thanks, this is interesting. This to_json method is much nicer than the to_dict method I saw e.g. [here](https://riptutorial.com/sqlalchemy/example/6614/converting-a-query-result-to-dict) because this does not couple together the members of the model and the "view model" automatically. In the example you provided, every model just has their own definition of a view model. Seems good to me! – Nanna Mar 05 '19 at 15:45
  • Please note my update changes how I would now approach this – Andrew Allen Apr 11 '19 at 07:15
  • Thank you, I will look into this. – Nanna Apr 11 '19 at 14:37