简体   繁体   中英

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

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

Note; remember parent _ _ id , not parent_id!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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