使用Peewee创建自引用表格

huangapple go评论62阅读模式
英文:

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&#39;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(&#39;self&#39;, null=True, backref=&#39;children&#39;)
    name = CharField()

Example use:

root = Department.create(name=&#39;root&#39;)
d1 = Department.create(parent=root, name=&#39;Dept 1&#39;)
# etc.

huangapple
  • 本文由 发表于 2023年2月14日 05:29:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75441359.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定