0

I have a Model with an auto-incrementing primary key. I want to be able to create an object from that model without an id, throw it away, and not have that Column's id auto-increment. Is that possible?

Assigning MyModel(id=None) does not do that.

Assigning MyModel(id=0) does not work either. It results in a Key (id)=(0) already exists. response.

To clarify: I want to keep the Column as auto-incrementing, but disable that behavior in specific circumstances.

The goal is to have a MyModel instance not saved in the database which I can pass to the template and can treat just like any other. For example, I want to print myModel.attribute in a template, but without saving myModel or incrememting the Column's id counter.

This is Postgres/Python/Flask/SQLAlchemy.

thekthuser
  • 706
  • 1
  • 12
  • 28
  • 1
    Please [edit] your question to explain what you intend to do with that instance of the model class. Autoincrement values are not assigned until you call `.flush()` or `.commit()` – Gord Thompson Jul 31 '22 at 08:37
  • "The goal is to have a MyModel instance not saved in the database" - Well, if you create an instance of the model, e.g., `foo = MyModel(…)` and do not use `session.add()` to attach it to a Session then it won't be persisted and therefore it won't affect the identity/serial/sequence value on the server. Would that work for you? – Gord Thompson Jul 31 '22 at 20:51
  • No, not including a `session.add()` doesn't fix it. The problem is the instance gets auto-flushed. I did find (multiple) solutions, though. I will post them in a minute. – thekthuser Jul 31 '22 at 23:53

1 Answers1

2

The problem is the instance is being auto-flushed. Not including session.add(myModel) does not fix it, but here are three solutions.

  1. session.autoflush=False
  • this isn't great because it applies to everything after that line
  1. session.expunge(myModel)
  • this might throw an exception and needs to be wrapped in a try/except
  1. from sqlalchemy.orm import make_transient and make_transient(myModel)
  • this is what I went with
thekthuser
  • 706
  • 1
  • 12
  • 28