[英]Can I change the value of a primary key with PonyORM?
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). 但我得到一个TypeError(不能更改主键属性值的值)。
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. 您可以将自动增量id
添加到Car
类作为主键,然后使您的number
唯一,并且您仍然可以在具有相同约束的情况下轻松更改它。
eg 例如
class Car(db.Entity):
id = PrimaryKey(int, auto=True)
number = orm.Required(str, 12, unique=True)
owner = orm.Required("Owner")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.