我需要更改实体中主键的原始值,但我无法执行此操作。例如:
#!/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")
但我得到一个TypeError(无法更改主键属性值的值)。
答案 0 :(得分:0)
主键理想情况下应该是不可变的。您可以将自动增量id
添加到Car
类作为主键,然后使number
唯一,并且您仍然可以轻松更改它,同时仍然具有相同的约束。
e.g。
class Car(db.Entity):
id = PrimaryKey(int, auto=True)
number = orm.Required(str, 12, unique=True)
owner = orm.Required("Owner")