[FIXED] How check if input element is already in query in Flask?

Issue

user input some tags, I have to chack if it is alredy in query and if not I save it. I have 2 different base, one for post, another for tag, and then I create post I use Tag bases objects. and if my post tag isnot in Tag’s base I create new record for it.

if tag_name not in tags:     
   new_tag = Tag(tag_name, user)
   db.session.add(new_tag)
   db.session.commit() 

this is how check and create new record but actually it doesnt work properly.

this is whole function:

def get_user(user_id):
user = User.query.filter_by(id = user_id).first()
tags = Tag.query.order_by(Tag.date_created).all()

# posts = Post.query.order_by(Post.date_created).all()
form = questionForm()

total_likes = 0
if user.posts:
    for likes in user.posts:        
        total_likes+=1

if form.validate_on_submit():
    user = current_user.id
    tag_name = request.form.get('tag_name')

    if tag_name not in tags:     
        new_tag = Tag(tag_name, user)
        db.session.add(new_tag)
        db.session.commit() 

    post = Post(form.heading.data, form.text.data, user, tag_name)

    db.session.add(post)
    db.session.commit()
    flash('posted succesfuly')

    return render_template("profile.html", user = user, form=form, total_likes = total_likes,tags = tags)

return render_template("profile.html", user = user, form=form, total_likes = total_likes, tags = tags)

whats my Tag class:

class Tag(db.Model):

__tablename__='tag'

id =db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(15), nullable = False, unique=True, index=True)
date_created = db.Column(db.DateTime, default = datetime.utcnow())
author = db.Column(db.Integer, db.ForeignKey('user.id', ondelete="CASCADE"), nullable=False)

def __init__(self, name, author, date_created = datetime.utcnow()):
    self.name=name
    self.author = author

my form class :

class questionUpdateForm(FlaskForm):
   heading = StringField('heading', [Length(min=2, max=50), 
             DataRequired(message='Question ')])
   # tag = StringField('Programming Language')
   text = StringField('Question', [Length(min=2, max=1000), 
           DataRequired(message='description')])

and jinja template :

<div >
    <label for="states">Choose or Create Tag</label>
    <input class="form-control" type="text"name='tag_name' id="tag_name" name="states" list="states-list" value={{update_post.tags}}>
      <datalist  id="states-list">
        {%for tag in tags%}
          <option>{{tag.name}}</option>    
        {%endfor%}       
      </datalist>            
 </div>    

Solution

What you need to do is something like this:

if tag_name not in {tag.name for tag in tags}: 
   new_tag = Tag(tag_name, user)
   db.session.add(new_tag)
   db.session.commit()

because right now you are just searching if the given name is in the tag objects, which doesn’t really make sense.

This will search if the tag_name is in the set of all distinct existing tag names.

Answered By – MarcusWilliams

Answer Checked By – Mildred Charles (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published