使用Peewee创建自引用表格

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

create Self Referencing Table using peewee

问题

  1. 我找不到一种使用Peewee创建自引用表的方法。我试图创建类似于[这篇文章][1]中描述的实体。
  2. [![在此输入图片描述][2]][2]
  3. 我尝试了这个解决方案[这里][3],但似乎不能给我想要的结果。
  4. [1]: https://www.codeproject.com/Tips/5255964/How-to-Create-and-Use-a-Self-referencing-Hierarchi
  5. [2]: https://i.stack.imgur.com/u542Q.png
  6. [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')

  1. <details>
  2. <summary>英文:</summary>
  3. 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].
  4. [![enter image description here][2]][2]
  5. I have tried this solution [here][3] and it doesn&#39;t seem to give me the results that I want.
  6. [1]: https://www.codeproject.com/Tips/5255964/How-to-Create-and-Use-a-Self-referencing-Hierarchi
  7. [2]: https://i.stack.imgur.com/u542Q.png
  8. [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')

  1. </details>
  2. # 答案1
  3. **得分**: 0
  4. 以下是翻译好的部分:
  5. 这些内容已经在这里记录下来:http://docs.peewee-orm.com/en/latest/peewee/models.html#self-referential-foreign-keys
  6. ```python
  7. class Department(BaseModel):
  8. parent = ForeignKeyField('self', null=True, backref='children')
  9. name = CharField()

示例用法:

  1. root = Department.create(name='root')
  2. d1 = Department.create(parent=root, name='Dept 1')
  3. # 等等。
英文:

These are documented here: http://docs.peewee-orm.com/en/latest/peewee/models.html#self-referential-foreign-keys

  1. class Department(BaseModel):
  2. parent = ForeignKeyField(&#39;self&#39;, null=True, backref=&#39;children&#39;)
  3. name = CharField()

Example use:

  1. root = Department.create(name=&#39;root&#39;)
  2. d1 = Department.create(parent=root, name=&#39;Dept 1&#39;)
  3. # 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:

确定