title: Sqlalchemy delete orphaned relation with one-to-many
body: <p>I have two tables, <code>User</code> and <code>Profiles</code>. A user can have many profiles. If the user is deleted all the profiles are deleted. However I want to also make it so if a user has no profiles the user is also delete (assume I always insert a user with at least one profile).</p>
  <p>I looked into delete-orphan but I'm not totally sure where I should put this or if it does what I need?</p>
  <p>Any help is appreciated.
  <a href="https://docs.sqlalchemy.org/en/13/orm/cascades.html#delete-orphan" rel="nofollow noreferrer">https://docs.sqlalchemy.org/en/13/orm/cascades.html#delete-orphan</a></p>
  <pre><code>class User(db.Model):
  
      __tablename__ = 'user'
  
      id = db.Column(db.Integer, primary_key=True, autoincrement=True)
      active = db.Column(db.Boolean(), default=True, nullable=False)
      created_date = db.Column(db.DateTime, default=func.now(), nullable=False)
      profile_ = db.relationship(&quot;Profile&quot;, back_populates=&quot;user_&quot;, cascade=&quot;all,delete&quot;)
  
  
  class Profile(db.Model):
  
      __tablename__ = 'profile'
  
      id = db.Column(db.Integer, primary_key=True, autoincrement=True)
      user_id = db.Column(db.Integer, db.ForeignKey(&quot;user.id&quot;), nullable=False)
      user_ = db.relationship(&quot;User&quot;, back_populates=&quot;profile_&quot;)
  </code></pre>