簡體   English   中英

Python Peewee 中同一個表的外鍵

[英]Foreign key to the same table in Python Peewee

我在 Python中將ORM peewee用於 sqlite。 我想創建帶有字段parent_idItem ,它將是Item外鍵:

from peewee import *

db = SqliteDatabase("data.db")

class Item(Model):
    id = AutoField()
    parent_id = ForeignKeyField(Item, null = True)

    class Meta:
        database = db

db.create_tables([Item])

但是,由於循環外鍵出現錯誤:

NameError:在封閉范圍內賦值之前引用了自由變量“Item”

對於這種情況,peewee 中有DeferredForeignKey

from peewee import *

db = SqliteDatabase("data.db")

class Item(Model):
    id = AutoField()
    parent_id = DeferredForeignKey("Item", null = True)

    class Meta:
        database = db

db.create_tables([Item])
Item._schema.create_foreign_key(Item.parent_id)

不幸的是,sqlite中沒有ADD CONSTRAINT ,所以出現了另一個錯誤:

peewee.OperationalError:靠近“CONSTRAINT”:語法錯誤

有沒有辦法使用peewee在sqlite中創建循環外鍵,或者我必須使用普通整數而不是外鍵或使用本機SQL而不是ORM?

這非常清楚地記錄在案: http : //docs.peewee-orm.com/en/latest/peewee/models.html#self-referential-foreign-keys

您只需將'self'作為標識符:

class Item(Model):
    id = AutoField()
    parent = ForeignKeyField('self', backref='children', null=True)

    class Meta:
        database = db

您不需要弄亂任何延遲密鑰或任何東西。

我找到了解決方案。 可以在Meta類中添加自定義約束:

from peewee import *

db = SqliteDatabase("data.db", pragmas = {"foreign_keys": "on"})

class Item(Model):
    id = AutoField()
    parent_id = IntegerField()

    class Meta:
        database = db
        constraints = [
            SQL("FOREIGN KEY(parent_id) REFERENCES items(id)")
        ]

db.create_tables([Item])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM