8
8
891099838382015-12-26 04:59:09
Flask
89109983838, 2015-12-26 04:59:09

Flask-sqlalchemy how to check\create\update rows in database?

Good time of the day!
I ran into this situation: a test project on Flask, it was necessary to save the settings of individual "modules" in the database, before that they were stored in .txt
and so there is a Setting table and its model in the database

class Setting(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    group = db.Column(db.String(32), nullable=False, default = 'NONE', index = True)
    key = db.Column(db.String(32), nullable=False, default = 'NONE', index = True)
    value = db.Column(db.Text)

I'm trying to implement such an algorithm:
- the function receives data from request.form, checks their presence in the database (by group);
- if absent, creates fields with data (group='setting', key='domain', value=request.form['domain'])
- if present, updates with values ​​(value) from request.form in the database
- and returns new ones (value) back to raiding the template!

Googling didn't turn up anything! , reading of.doc sqlalchemy too!!
probably not there "digging ...."
#......
if request.method == 'POST':
        data = db.session.query(Setting).filter_by(group='setting').first()
        if not data:
            db.session.add_all([Setting(group='setting', key='domain', value=request.form['domain']),
                    Setting(group='setting', key='name', value=request.form['name']),
                    Setting(group='setting', key='title', value=request.form['title']),
                    Setting(group='setting', key='mdescription', value=request.form['mdescription']),
                    Setting(group='setting', key='mkeywords', value=request.form['mkeywords']),
            db.session.commit()
        # .....--- здесь наверно должен быть некий код для обновление строк в базе, ток как написать незнаю чтоб обновить сразу 4 строки в базе :(
        db.session.commit()
        test = db.session.query(Setting).filter_by(group='setting').all()
        return render_template('setting.html', test=test)


And just simply:
How to delete lines, for example, you need to delete all lines where group='setting'????

##### Clarification#######
with deletion got it! thank you very much!

1) Do I correctly check the existence of records, maybe there is a more specific option (without unloading the data itself, you need to get only True or False, and not the data itself)
data = db.session.query(Setting).filter_by(group='setting').first()
        if not data:


2) and yet how to update the data in the database and in different rows? In the test case above, this part is completely omitted! .... or from the beginning you need to find these records in the database and only then update each separately by id?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
8
89109983838, 2015-01-01
@89109983838

Here, after the selection and analysis of parameters and situations, the result is this:
(I would be grateful if someone adds edits on optimization in the comments)
we have a form with fields for the type:

<input name=domain type="text" value="{{ data.domain }}">
<input name=name type="text" value="{{data.name}}">
.......... и так далее..... вьюшка получилась универсальна - 
можно хоть сотни input добавлять прямо в шаблоне, 
главное чтоб имена были у всех разные

now the view itself checks for input - it exists in the database, then updates its value - if not, it creates it with the parameters sent.
app.route('/setting/', methods=['GET', 'POST', 'DELETE'])
def setting():
    if not session.get('logged_in'): # проверяем залогин ли usr
        abort(404)                        
    if request.method == 'DELETE':  # Если метод HTTP = DELETE удаляем настройки для группы setting
        db.session.query(Setting).filter_by(group='setting').delete() 
        db.session.commit()
        return render_template('setting.html')
    data = {} #создаем словарь - в нем собираем данные и отправляем обратно в форму (так как разложить data = db.session.query(Setting).all() в шаблоне без переборов у меня не хватило ума... :(  , а так по-моему проще )
    if request.method == 'POST':
        for i in request.form.keys(): # обрабатываем каждый input по отдельности
            u = db.session.query(Setting).filter_by(group='setting').filter_by(key=i).first()
            if u: # если существует обновляем значением из form
                u.value = request.form[i]                 
                data[i] = request.form[i] # добавляем в словарь
            else:
                db.session.add(Setting(group='setting', key=i, value=request.form[i])) # в противном случае создаем новое поле в базе данных и добавляем обратно в словарь
                data[i] = request.form[i]
        db.session.commit() # Записать изменения в Базу данных
        return render_template('root/setting.html', data=data)  # как видите словарь ушел обратно к темплею, в указном выше примере показано как словарь раскладывается....
    u = db.session.query(Setting).filter_by(group='setting').all()   # Ну а пи простом GET запросе выгружаем все записи по группе, создаем словарь и отправляем на рендринг
    for i in u:        
        data[i.key]=i.value
    return render_template('root/setting.html', data=data)

As a result:
I need to add a line to the database to store the settings of some module
- I add the next input to its group, respectively, only warmer
- and it works immediately !!!!!
By the way, the table looks like this in models.py:
class Setting(db.Model):
    id = db.Column(db.Integer,primary_key = True)
    group = db.Column(db.String(32), nullable=False, default = 'NONE', index = True)
    key = db.Column(db.String(32), nullable=False, default = 'NONE', index = True)
    value = db.Column(db.Text, index = True)
    
    def get_id(self):
        return self.id
        
    def __unicode__(self):
        return self.id

S
sim3x, 2015-12-26
@sim3x

How to delete rows, for example, you need to delete all rows where group='setting'?

docs.sqlalchemy.org/en/latest/orm/query.html#sqlal...
db.session.query(Setting).filter_by(group='setting').delete()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question