Hi

I'm struggling with an SQLAlchemy issue.

I have a one to many relationship like so:

users_tags = Table(
    "users_tags", Base.metadata,
    Column("user_id", Integer, ForeignKey("users.id")),
    Column("tag_id", Integer, ForeignKey("tags.id"))
)

class Tag(Base):
    __tablename__ = "tags"

    id = Column(Integer(), primary_key=True)
    name = Column(String(255), nullable=False, unique=True)


class User(Base):
    __tablename__ = "users"

    id = Column(Integer(), primary_key=True)
    name = Column(String(255), nullable=False)
    tags = relationship("Tag", secondary=users_tags, cascade="all, delete",
                        single_parent=True, backref=backref("user", cascade=
"all"),
                        lazy="subquery")


If I do the following:

tag = Tag()
tag.name = "C"

user = User()
user.name = "A"
user.tags.append(tag)
session.add(user)

user2 = User()
user2.name = "B"
user2.tags.append(tag)
session.add(user2)

session.commit()


I have two rows in users, two in users_tags and 1 in tags - as expected.

I then do:

userdel = session.query(User).filter_by(name="A").first()
session.delete(userdel)
session.commit()


And I end up with 3 empty tables in my DB.  I want to still have 1 entry in 
users, 1 in users_tags and 1 in tags.

The problem clearly comes from trying to maintain uniqueness within the 
tags table.  The cascading delete is removing the single entry from the 
tags table which in turn is deleting the other user who is using that tag.

How can I achieve what I want without having to have duplicate entries in 
the tags table?

Thanks in advance!

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to