Append new items in database only
<p>I have a table called <code>classes</code>
Which has fields:</p>

<p><code>course name</code><br>
 <code>times_mentioned</code></p>

<p>So what I'm trying to do is. Set <code>course_name</code> and <code>times_Mentioned</code> to null at first.
But when a user for instance in my website chooses a class, I just want to append that class name and keep adding +1 to <code>times_mentioned</code> for a specific class.  </p>

<p>This is what I have so far</p>

<pre><code>class popular_courses(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(80), unique=True, default=None)
    times_mentioned =db.Column(db.String(80), default=None, unique=True)
    def __repr__(self):
        return '&lt;Popular Courses %r&gt;' % (self.name) 

@app.route('/add/&lt;coursename&gt;')
def AddCourseName(coursename):
    addPopularCourse = popular_courses(name=coursename, times_mentioned=##DONT KNOW THE SYNTAX)
</code></pre>

<p>So like I'd want class name and add +1 every time the user visits /add URL. How would I do it? I don't know the syntax for it either.</p>

<p>@app.route('/add/')</p>

<pre><code>def AddCourseName(coursename):
    try:
        addPopularCourse = popular_courses(name=coursename, times_mentioned=1)
        db.session.add(addPopularCourse)
        db.session.commit()
        return "added! " +  coursename + " to db"
    except exc.SQLAlchemyError:
        db.session.rollback()
        user = popular_courses.query.filter_by(name=coursename).first()
        user.name = coursename
        user.times_mentioned += 1
        db.session.commit()
</code></pre>

<p>Is this the efficient approach?</p>

<p>1- change type of <code>times_mentioned</code> to <code>integer</code></p>

<p>2- use <code>count</code> func to check if instance exist if so increase counter else create a new one</p>

<pre><code>def AddCourseName(coursename):
    if db.session.query(popular_courses.id).filter(popular_courses.namââe==coursename).countââ() &gt; 0:
        course = popular_courses.query.filter_by(name=coursename).first()
        course.name = coursename
        course.times_mentioned += 1
        db.session.commit()
        return "increased by 1! "
    else:
        addPopularCourse = popular_courses(name=coursename, times_mentioned=1)
        db.session.add(addPopularCourse)
        db.session.commit()
        return "added! " +  coursename + " to db"
</code></pre>

python database syntax sqlalchemy