SQLAlchemy:如何删除一对多关系中的项目?

时间:2022-01-23 22:42:59

I am using SQLAlchemy, and i want to delete certain item in a one-to-many-relationship. Well there are two pictures for you. First you can see an EER-Model. Its a one (gender) to many (person) relation.

我正在使用SQLAlchemy,我想删除一对多关系中的某些项目。那么你有两张照片。首先,您可以看到EER模型。它是一个(性别)到多个(人)的关系。

SQLAlchemy:如何删除一对多关系中的项目?

Second, you can see a table with fictional data. In gender-table we have two gender currently, and in person-table we have three persons. SQLAlchemy:如何删除一对多关系中的项目?

其次,您可以看到包含虚构数据的表格。在性别表中,我们目前有两个性别,在人员表中我们有三个人。

Imagine, you will just delete a gender, let us say 'male'. But we see, that 'male' is used as foreign by person-table.

想象一下,你只会删除一个性别,让我们说'男性'。但是我们看到,“男性”被人们用作外国人。

My current source code looks as follows:

我目前的源代码如下:

class PERSON_GENDER(Base):

    __tablename__ = "person_gender"

    id = Column(Integer, primary_key=True, unique=True, autoincrement=True)
    gender = Column(String(50), nullable=False, unique=True)

class PERSON(Base):

    __tablename__ = "person"

    id = Column(Integer, primary_key=True, unique=True, autoincrement=True)
    nickname = Column(String(255))
    alias_name  = Column(String (255))
    name_normally_used = Column(String(50), nullable=False)
    first_middle_name = Column(String(255))
    last_name = Column(String(100))
    birth_name = Column(String(100))
    body_height = Column(String(10))
    wedding_anniversary = Column(Date)
    birthday = Column(Date)
    day_of_death = Column(Date)
    notice = Column(Text())

    gender_id = Column(Integer, ForeignKey('person_gender.id', ondelete='CASCADE'))
    gender = relationship("PERSON_GENDER", single_parent=True, cascade="all, delete, delete-orphan")

When I run this one, then not only the gender is deleted, but also the person. I want that only the gender is deleted, not the person.

当我运行这个时,不仅删除了性别,还删除了该人。我希望只删除性别,而不是个人。

1 个解决方案

#1


1  

ondelete='CASCADE')=> ondelete='SET NULL')

ondelete ='CASCADE')=> ondelete ='SET NULL')

#1


1  

ondelete='CASCADE')=> ondelete='SET NULL')

ondelete ='CASCADE')=> ondelete ='SET NULL')