英文:
create Self Referencing Table using peewee
问题
我找不到一种使用Peewee创建自引用表的方法。我试图创建类似于[这篇文章][1]中描述的实体。
[![在此输入图片描述][2]][2]
我尝试了这个解决方案[这里][3],但似乎不能给我想要的结果。
[1]: https://www.codeproject.com/Tips/5255964/How-to-Create-and-Use-a-Self-referencing-Hierarchi
[2]: https://i.stack.imgur.com/u542Q.png
[3]: https://stackoverflow.com/a/47894549/6211470
class Customer(Model):
name = TextField()
class CustomerDepartment(Model):
refid = ForeignKeyField(Customer, related_name='customer')
id = ForeignKeyField(Customer, related_name='department')
<details>
<summary>英文:</summary>
I am failing to find a way I can create a self-referencing table using peewee. I am trying to create an entity similar to one on [this article][1].
[![enter image description here][2]][2]
I have tried this solution [here][3] and it doesn't seem to give me the results that I want.
[1]: https://www.codeproject.com/Tips/5255964/How-to-Create-and-Use-a-Self-referencing-Hierarchi
[2]: https://i.stack.imgur.com/u542Q.png
[3]: https://stackoverflow.com/a/47894549/6211470
class Customer(Model):
name = TextField()
class CustomerDepartment(Model):
refid = ForeignKeyField(Customer, related_name='customer')
id = ForeignKeyField(Customer, related_name='department')
</details>
# 答案1
**得分**: 0
以下是翻译好的部分:
这些内容已经在这里记录下来:http://docs.peewee-orm.com/en/latest/peewee/models.html#self-referential-foreign-keys
```python
class Department(BaseModel):
parent = ForeignKeyField('self', null=True, backref='children')
name = CharField()
示例用法:
root = Department.create(name='root')
d1 = Department.create(parent=root, name='Dept 1')
# 等等。
英文:
These are documented here: http://docs.peewee-orm.com/en/latest/peewee/models.html#self-referential-foreign-keys
class Department(BaseModel):
parent = ForeignKeyField('self', null=True, backref='children')
name = CharField()
Example use:
root = Department.create(name='root')
d1 = Department.create(parent=root, name='Dept 1')
# etc.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论