0

我有两张桌子,imagerestaurant。我已经在它们之间建立了多对多的关系。

以下是表定义的相关部分:

images_assoc = Table('restaurant_image_assoc', Base.metadata,
        Column('restaurant', Integer(unsigned=True),
            ForeignKey('restaurant.id')),
        Column('image', Integer(unsigned=True),
            ForeignKey('image.id')))

class Image(Base):
    __tablename__ = 'image'
    id = Column(Integer(unsigned=True), primary_key=True)
    reports = Column(TinyInt, nullable=False, default=0)
    created_at = Column(DateTime, default=datetime.now)

class Restaurant(Base):
    __tablename__ = 'restaurant'
    id = Column(Integer(unsigned=True), primary_key=True)
    images = relationship(Image, secondary=images_assoc)

我需要删除 中的一行,但当然我需要先删除指向它image的所有行。restaurant_image_assoc我该怎么做呢?

我试过这个:

request.db.query(images_assoc)\
        .filter(images_assoc.c.image==image.id).delete()
request.db.delete(image)
request.db.commit()

image我要删除的行在哪里,但出现此错误:

AttributeError: 'Table' object has no attribute 'class_'
4

2 回答 2

0

The issue is that SA does not track the relationship between Restaurant and the Image from the side of the Image, and therefore it "does not know" that there is a dependency. As soon as you configure the relationship from the other side, the respective rows in the association table will be also deleted automatically. In order to add the other side of the relationship it is enough to simply use the backref:

class Restaurant(Base):
    images = relationship(Image, secondary=images_assoc, backref="restaurants")

but you can also define those explicitly on each object (back_populates is required in this case):

class Image(Base):
    restaurants = relationship("Restaurant", secondary=images_assoc, back_populates="images")
class Restaurant(Base):
    images = relationship(Image, secondary=images_assoc, back_populates="restaurants")

But the latter is semantically the same as using backref.

于 2012-06-13T08:51:35.990 回答
0

如果您删除图像中的一行,您应该获得该图像 ID。然后你可以在你的关联表中删除图像 id == 你的图像 id。

于 2012-06-12T21:36:05.413 回答