【问题标题】:Can I change the value of a primary key with PonyORM?我可以使用 PonyORM 更改主键的值吗?
【发布时间】:2017-06-11 09:06:44
【问题描述】:

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

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

【问题讨论】:

    标签: python database-design ponyorm


    【解决方案1】:

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

    例如

    class Car(db.Entity):
        id = PrimaryKey(int, auto=True)
        number = orm.Required(str, 12, unique=True)
        owner = orm.Required("Owner")
    

    【讨论】:

      猜你喜欢
      • 2015-04-04
      • 1970-01-01
      • 2016-09-16
      • 2022-07-11
      • 1970-01-01
      • 2017-08-21
      • 2010-10-08
      • 1970-01-01
      • 2010-10-01
      相关资源
      最近更新 更多