Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 项目和类别数据库关系_Python_Sqlalchemy - Fatal编程技术网

Python 项目和类别数据库关系

Python 项目和类别数据库关系,python,sqlalchemy,Python,Sqlalchemy,所以我想让用户添加一个项目和任意类别。现在我使用if语句来确保类别是否已经创建,而不是再次添加。有没有更好的方法来利用SQLAlchemy关系,这样我就可以跳过一些必须编写的逻辑,以确保类别是唯一的 以下是我使用的模型: class Category(Base): __tablename__ = 'category' id = Column(Integer, primary_key=True) name = Column(String(250), nullable=Fal

所以我想让用户添加一个项目和任意类别。现在我使用if语句来确保类别是否已经创建,而不是再次添加。有没有更好的方法来利用SQLAlchemy关系,这样我就可以跳过一些必须编写的逻辑,以确保类别是唯一的

以下是我使用的模型:

class Category(Base):
    __tablename__ = 'category'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

class Item(Base):
    __tablename__ = 'item'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)
    description = Column(String)
    category_id = Column(Integer, ForeignKey('category.id'))
    category = relationship(Category)
    date_created = Column(DateTime)
    date_updated = Column(DateTime)
    user_id = Column(Integer, ForeignKey('user.id'))
    user = relationship(User)
以下是如何编辑项目的示例:

if new_category_name != category.name:
    if db_session.query(Category).\
        filter_by(name=new_category_name).count() == 0:
        new_category = Category(name=new_category_name)
    else:
        new_category = db_session.query(Category)\
            .filter_by(name=new_category_name).one()

    is_last_of_category = db_session.query(Item)\
        .filter_by(category_id=item.category_id).count() == 1
    if is_last_of_category:
        db_session.delete(category)
        item.category = new_category
db_session.commit()

您愿意提出的任何其他建议,我都乐意听取。

使用
独特的
约束

引用sqlalchemy的

唯一–如果为True,则表示此列包含唯一 约束,或者如果索引也为True,则指示索引 应使用唯一标志创建。在中指定多个列的步骤 约束/索引或要指定显式名称,请使用 明确的唯一约束或索引构造

sqlalchemy的示例:


有了这个,我可以不用检查一个新的类别吗?是的,但是你应该试试,因为如果有人试图创建一个重复的数据,它会抛出异常,您应该能够安全地处理它。如果我删除的项目恰好是类别的最后一项,它还会自动删除该类别吗?
db\u session.delete(user\u object)
from sqlalchemy import UniqueConstraint

meta = MetaData()
mytable = Table('mytable', meta,

    # per-column anonymous unique constraint
    Column('col1', Integer, unique=True),

    Column('col2', Integer),
    Column('col3', Integer),

    # explicit/composite unique constraint.  'name' is optional.
    UniqueConstraint('col2', 'col3', name='uix_1')
    )