title: Update SQLAlchemy ORM existing model from posted Pydantic model in FastAPI?
body: <p>I want to expose an API method that receives data in a POST request (for a beta signup API), and upsert with new values when there's already a matching model. What's the best way to achieve this? Currently I'm doing this (somewhat simplified):</p>
  <p>My ORM model (SqlAlchemy):</p>
  <pre class="lang-python prettyprint-override"><code>class BetaORM(Base):
      __tablename__ = &quot;betasignup&quot;
      email = Column(EmailType, primary_key=True)
      fullname = Column(String, unique=False, index=False, nullable=True)
  </code></pre>
  <p>My Pydantic model:</p>
  <pre class="lang-python prettyprint-override"><code>class BetaCreate(BaseModel):
      email: EmailStr
      fullname: Optional[str]
  </code></pre>
  <p>My FastAPI post method:</p>
  <pre class="lang-python prettyprint-override"><code>@app.post(&quot;/beta_signup&quot;)
  def post_beta_signup(beta: schemas.BetaCreate, db: Session = Depends(get_db)):
      return create_beta_signup(db=db,signup=beta)
  </code></pre>
  <p>And the CRUD method I've written:</p>
  <pre class="lang-python prettyprint-override"><code>def create_beta_signup(db: Session, signup: schemas.BetaCreate):
      db_beta = schemas.BetaORM(**signup.dict())
      ret_obj = db.merge(db_beta)
      db.add(ret_obj)
      db.commit()
      return ret_obj
  </code></pre>
  <p>One problem with using merge() is that it relies on matching with primary key, directly against the email address - I'd much rather use a <a href="https://en.wikipedia.org/wiki/Surrogate_key" rel="noreferrer">surrogate key</a> instead, so that I can have a disable / delete functionality and not be forced to have a unique constraint on the email address at the database level.</p>