Home > Back-end >  Checking value inside Sqlalchemy queried data
Checking value inside Sqlalchemy queried data

Time:11-30

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

CodePudding user response:

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
  • Related