cbron
cbron

Reputation: 4044

How do you delete just one row in sql-alchemy without deleting any of its relationships

I'm having problems with dependancy rules. For the life of me I can't figure out how to delete just one row without deleting its relationships.

Tables:

User
 -id
 -name
Article
  -id
  -title
UserArticle
  -id
  -user_id
  -article_id

Depending on my cascade rules, running this either deletes the User and Article associated with it or simply errors out with an AssertionError.

ua = UserArticle.query.first()
db.session.delete(ua)
db.session.commit()

Here's one of the relationships.

class UserArticle(db.Model):
  user = relationship("User",
  primaryjoin="UserArticle.user_id==User.id",
  foreign_keys="User.id")

Yes I have read the casecade rules, no I don't understand them. http://docs.sqlalchemy.org/en/latest/orm/session.html#cascades

How can I just delete that record and nothing else ?

Upvotes: 0

Views: 80

Answers (1)

pmccallum
pmccallum

Reputation: 808

A cascade rule means that any records that have been orphaned by your deletion should also be deleted.

When you delete a UserArticle a User (in the eyes of the program) has no reason to exist anymore. This looks like it's a problem with your database model.

Try defining your model using...

class UserArticle(db.Model):
    id = db.Column(db.Integer, primary_key=True, auto_increment=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    article_id = db.Column(db.Integer, db.ForeignKey('articles.id'))

    creator = db.relationship("User", backref="UserArticle", primaryjoin=(user == User.id))

I'm assuming in this code that your users and articles are mapped to the "users" and "articles" table respectively.

Upvotes: 1

Related Questions