1

Apologies if this is poorly phrased as I'm pretty new to SQLAlchemy. Suppose I have the following setup:

class Student(Base):
    __tablename__ = 'student'
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    name =  Column(String(50), nullable=False)

...and I create a new Student and add it to the table:

new_student = Student(name="Nick")
session.add(new_student)
session.commit()

Assuming that primary key is solely the UUID, how can I check the table for the existence of the specific object referenced by new_student? Is it possible to do something like:

student = session.query(Student).filter(new_student)

Everything I've seen in my searches requires you to use a table column, but the only guaranteed unique column in my table is the UUID, which I don't know until after it's created.

Thanks for the help!

Nick
  • 41
  • 2
  • If I remember correctly, `new_student.id` might get set by `session.add()` and `commit()`. I think SQLAlchemy issues an `INSERT ... RETURNING` query to accomplish that. Don't have time to test that myself. – Dan Getz May 18 '22 at 18:52
  • Calling `session.flush()` after `session.add(...)` should set the primary key value on the object. – snakecharmerb Jun 03 '22 at 15:34

0 Answers0