我可以使用PonyORM更改主键的值吗?

时间:2017-06-11 09:06:45

标签: python database-design ponyorm

我需要更改实体中主键的原始值,但我无法执行此操作。例如:

#!/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(无法更改主键属性值的值)。

1 个答案:

答案 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")
相关问题