I need to change the original values of primary keys in a entity, but I am unable to do it. For example:
#!/usr/bin/env python3
# vim: set fileencoding=utf-8
from pony import orm
db = orm.Database("sqlite", ":memory:", create_db=True)
class Car(db.Entity):
number = orm.PrimaryKey(str, 12)
owner = orm.Required("Owner")
class Owner(db.Entity):
name = orm.Required(str, 75)
cars = orm.Set("Car")
db.generate_mapping(create_tables=True)
with orm.db_session:
luis = Owner(name="Luis")
Car(number="DF-574-AF", owner=luis)
with orm.db_session:
car = Car["DF-574-AF"]
# I try to change the primary key
car.set(number="EE-12345-AA")
But I get a TypeError (Cannot change value of primary key attribute number).
The primary key should ideally be immutable. You can add an auto-incremental id
to your Car
class as a primary key, then make your number
unique and you will be able to change it easily while still having the same constraints.
eg
class Car(db.Entity):
id = PrimaryKey(int, auto=True)
number = orm.Required(str, 12, unique=True)
owner = orm.Required("Owner")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.