1

我需要更改实体中主键的原始值,但我无法做到。例如:

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

4

1 回答 1

0

理想情况下,主键应该是不可变的。您可以将自动增量添加id到您的Car类中作为主键,然后使您的number唯一,您将能够轻松更改它,同时仍然具有相同的约束。

例如

class Car(db.Entity):
    id = PrimaryKey(int, auto=True)
    number = orm.Required(str, 12, unique=True)
    owner = orm.Required("Owner")
于 2018-03-13T12:00:56.463 回答