简体   繁体   English

在 Django 中查询自引用表

[英]querying a self referencing table in Django

I have a model which references itself so that I have a parent / child relationship between users in the db.我有一个引用自身的模型,以便我在数据库中的用户之间建立父/子关系。 A parent can have multiple children, but a child can only have one parent.一个父母可以有多个孩子,但一个孩子只能有一个父母。

Firstly, is this the correct way to define the model:首先,这是定义模型的正确方法:

class User(models.Model):
   name = models.CharField(max_length=50)
   parent = models.ForeignKey('self')

Secondly, I need to query the model and return all the children of a particular parent.其次,我需要查询模型并返回特定父级的所有子级。 I have read some articles on tree structures where queries can be more complicated.我已经阅读了一些关于树结构的文章,其中查询可能更复杂。 But given I only need one layer deep, will this return all the children:但鉴于我只需要一层深,这是否会返回所有孩子:

children = User.objects.get(parent=PARENT_ID)

where PARENT_ID is obviously the id of the parent其中 PARENT_ID 显然是父级的 id

Yes, you can use like your code.是的,你可以像你的代码一样使用。

and Yes again, but little bit different.是的,但又有点不同。

children = User.objects.filter(parent__id=PARENT_ID)

You can find children with parent__id您可以找到具有parent__id孩子

Note;笔记; remember parent _ _ id , not parent_id!记住父母 _ _ id ,而不是 parent_id!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM