Setting ID on the new model

Is it possible to create a new instance of the model and set its ID? Whenever I try to do this, the model is saved, but the identifier is set to the next available number in the MySQL auto-increment list.

For example, I want to create a new sensor as follows:

s = new Sensor()
s.id = 14
s.name = 'my sensor'
db.session.add(s)
db.session.commit()

saved_instance = Sensor.query.get(14)
assert saved_instance is not None

The statement fails.

+4
source share
1 answer

I'm going to go to a limb (since you did not provide information that will tell me for sure), but I believe that your sensor declaration uses auto-increment. If this is the case, then installing it before your hand will be completely ignored.

sensor = Table('sensor', metadata,
    Column('id', Integer, primary_key = True),

MySQL .

( MySQL), 14 - , . , 14.

, , .

s = new Sensor()
s.id = 14
s.name = 'my sensor'
db.session.add(s)
db.session.commit()

saved_instance = Sensor.query.get(14)
print(saved_instance is not None) # Should fail.

print(s.id) # will return the ID that was actually inserted.
s.update().\
    where(users.c.id==s.id).\
    values(id=14)
+1

All Articles