Note that there are some explanatory texts on larger screens.

plurals
  1. POFlask-SQLAlchemy: How to conditionally insert or update a row
    primarykey
    data
    text
    <p>My application uses a combination of Flask, Flask-SQLAlchemy, Flask-WTF and Jinja2.</p> <p>In its current incarnation, I have a settings table. The table will only have one record with one field. Initially the table contains zero records. </p> <p>What I want to achieve is:</p> <ul> <li>Given that no entries exist in db, then show empty form ready for user input</li> <li>Given that an entry exist, show the entry, and</li> <li>if the user changes the value, then update the rec in db.</li> </ul> <p>Here is my code:</p> <p><strong>models.py</strong></p> <pre><code>class Provider(db.Model): id = db.Column(db.Integer, primary_key = True) rssfeed = db.Column(db.String(120), unique = True) def __init__(self, rssfeed): self.rssfeed = rssfeed def __repr__(self): return '&lt;NZBMatrix feed url %r&gt;' % self.rssfeed </code></pre> <p><strong>forms.py</strong></p> <pre><code>class SettingsForm(Form): rssfeed = TextField('rssfed', validators= [Required()]) </code></pre> <p><strong>views.py</strong></p> <pre><code> @app.route('/settings', methods=["GET","POST"]) def settings(): """ show settings """ provider = Provider.query.get(1) form = SettingsForm(obj=provider) print provider if request.method == "POST" and form.validate(): if Provider.query.get(1) is None: provider = Provider(rssfeed=form.rssfeed.data) form.populate_obj(provider) db.session.add(provider) db.session.commit() flash("Settings added") return render_template("settings.html", form=form) </code></pre> <p>As it stands this code creates a record if it doesn't exists but the <code>rssfeed</code> column is empty. </p> <p>How can I change this code so that it will <code>INSERT</code> if the record doesn't exist and <code>UPDATE</code> if it does?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload