Django self-referential foreign key

对着背影说爱祢 提交于 2019-11-26 10:36:28

问题


I\'m kind of new to webapps and database stuff in general so this might be a dumb question. I want to make a model (\"CategoryModel\") with a field that points to the primary id of another instance of the model (its parent).

class CategoryModel(models.Model):
    parentId = models.ForeignKey(CategoryModel)

How do I do this? Thanks!


回答1:


You can pass in the name of a model as a string to ForeignKey and it will do the right thing.

So:

parentId = models.ForeignKey("CategoryModel")

Or you can use the string "self"

parentId = models.ForeignKey("self")



回答2:


You can use the string 'self' to indicate a self-reference.

class CategoryModel(models.Model):
    parentId = models.ForeignKey('self')

https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey




回答3:


https://books.agiliq.com/projects/django-orm-cookbook/en/latest/self_fk.html

class Employee(models.Model):
    manager = models.ForeignKey('self', on_delete=models.CASCADE)

OR

class Employee(models.Model):
    manager = models.ForeignKey("app.Employee", on_delete=models.CASCADE)

https://stackabuse.com/recursive-model-relationships-in-django/



来源:https://stackoverflow.com/questions/15285626/django-self-referential-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!