Checking value inside Sqlalchemy queried data

Question:

I am querying Tags table and storing its values into varialble

all_tags = Tag.query.all() # <- Query all existing tags

Output:

>>> all_tags
[<Tag>: STM32, <Tag>: Linux, <Tag>: Unix, <Tag>: Skype, <Tag>: MCU, <Tag>: CPU, <Tag>: Silk, <Tag>: WAN]

I am receiving tag values from json client, after I want to skip existiing tags and add only news to database.

for tag in json_data['tags']:
      tag = Tag(tag_name=tag)
      if tag in all_tags: # <- If tag from json query does exists in table skip
        pass
      myPost.tags.append(tag) # < - or add it

Seems this code doesnot work and throws the error:

sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: tags.tag_name

Please, advice how can I implement this task

Asked By: ussrback

||

Answers:

You can query for every id, if exists skip the append operation, otherwise append it.

for tag in json_data['tags']:
      tag_q = Tag.query.filter_by(id=tag["id"]).first()
      if tag_q is not None:
        continue
      myPost.tags.append(tag_q) # < - or add it
Answered By: Matteo Pasini
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.