Reputation: 1602
I am creating a web application using flask and sqlalchemy.
I am confused about putting db_session related statements like db_session.add(). There are two approaches I am thinking of. One is to create an add() function in model itself and encapsulate sqlalchemy part completely. Another approach is to call those functions from controller. While looking at many examples of models, I can see that mostly second approach is used. Which is better/correct way of doing this and why?
e.g.1) In model itself
class Events(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(128))
.
.
.
def add(self):
db.session.add(self)
db.session.commit()
def delete(self):
db.session.delete(self)
db.session.commit()
class EventsAPI(MethodView):
def get(self, event_id):
e = Events()
e.title = 'testing'
e.add()
.
.
.
2) In Controller
class Events(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(128))
.
.
.
class EventsAPI(MethodView):
def get(self, event_id):
e = Events()
e.title = 'testing'
db.session.add(e)
db.session.commit()
.
.
.
Upvotes: 2
Views: 401
Reputation: 5344
In the second case, you can save several records in one transaction and rollback it if something goes wrong. It seems logical for me to use session mostly in controllers, at least that is what I've done in my previous project. Primarily because the transactions and error handling code looked more explicit that way.
On the other hand, you can use sub-transactions and there is Django ORM that has model.save
, model.delete
functions. And controllers look cleaner that way.
There are always pros and cons. I would suggest to write a couple of different controllers and look what approach works better for your project. Don't forget to handle exceptions. If you'll decide to use the first approach, make a BaseModel class with common for all your models methods.
Upvotes: 1
Reputation: 33289
In general, yes you should put those in the View/Controller. The reason is that the logic of the application should be in the View/Controller. Usually, you will add/remove/delete/update etc. through your View/Controller and that is where you should put all this.
Upvotes: 0