Flask SQLAlchemy 查询仅在第一次工作

Flask SQLAlchemy Query Only working the first time

我正在尝试检查标签是否已存储在 table 中。查询找到第一个标签,但没有找到第二个标签,并且都已在 table.

中退出
        tags = form.tags.data
        tags = tags.split(sep=",")
        tag: str
        for tag in tags:
            # Register the tag if it is not already stored
            tag_aux = Tags.get_by_tag(tag, language)
            if tag_aux is None:
                tag_id = Tags(None, tag.strip(), language).save()
                TagsPosts(post.id, tag_id).save()
            else:
                TagsPosts(post.id, tag_aux.id).save()
        # commit
        TagsPosts.commit()

循环遍历从表单中检索到的标签列表并检查它是否已经存在。 tag_aux 如果该值已存在于数据库中,则获取该值。

#  Table Mapping
__tablename__ = 'tags'
id = db.Column(db.Integer, primary_key=True)
description = db.Column(db.String, nullable=False)
language_id = db.Column(db.String, nullable=False)

def __init__(self, arg_id, description, language_id):
    self.id = arg_id
    self.description = description
    self.language_id = language_id

#  Gets a tag by description and language
@staticmethod
def get_by_tag(description, language_id):
    """Used to check if a tag already exists"""
    return Tags.query.filter_by(description=description,language_id=language_id).first()

令人惊讶的是,找到了第一个标签,但没有找到第二个标签,因此 tag_aux 在第二个循环中得到 None。

  1. 查询
   kwargs = {dict: 2} {'description': 'Te', 'language_id': 'ES'}
   self = {BaseQuery} SELECT tags.id AS tags_id, tags.description AS tags_description,      tags.language_id AS tags_language_id \nFROM tags
  1. 查询
  kwargs = {dict: 2} {'description': ' Inglaterra', 'language_id': 'ES'}
  self = {BaseQuery} SELECT tags.id AS tags_id, tags.description AS tags_description,   tags.language_id AS tags_language_id \nFROM tags

table

提前致谢。

正如我在评论中提到的,查询的字符串包含额外的space。我会按如下方式修复代码(和小的重构)

tags: List[str] = form.tags.data.split(",")
for tag in tags:
    tag = tag.strip()
    # Register the tag if it is not already stored
    tag_aux = Tags.get_by_tag(tag, language)
    if tag_aux is None:
        tag_id = Tags(None, tag, language).save()
        TagsPosts(post.id, tag_id).save()
    else:
        TagsPosts(post.id, tag_aux.id).save()
# commit
TagsPosts.commit()