Python Django自引用外键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15285626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django self-referential foreign key
提问by sfendell
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).
我对 webapps 和数据库的东西一般都是新手,所以这可能是一个愚蠢的问题。我想制作一个模型(“CategoryModel”),其字段指向模型的另一个实例(其父级)的主 ID。
class CategoryModel(models.Model):
parent = models.ForeignKey(CategoryModel)
How do I do this? Thanks!
我该怎么做呢?谢谢!
采纳答案by Jared Forsyth
You can pass in the name of a model as a string to ForeignKey and it will do the right thing.
您可以将模型的名称作为字符串传递给 ForeignKey,它会做正确的事情。
So:
所以:
parent = models.ForeignKey("CategoryModel")
Or you can use the string "self"
或者您可以使用字符串“self”
parent = models.ForeignKey("self")
回答by Brandon
You can use the string 'self' to indicate a self-reference.
您可以使用字符串“self”来表示自引用。
class CategoryModel(models.Model):
parent = models.ForeignKey('self')
https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey
https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey
回答by Hailee
https://books.agiliq.com/projects/django-orm-cookbook/en/latest/self_fk.html
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://stackabuse.com/recursive-model-relationships-in-django/
回答by Punnerud
You also to sett null=True and blank=True
您还可以设置 null=True 和 blank=True
class CategoryModel(models.Model):
parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True)
null=True, to allow in database
blank=True, to allow in form validation
null=True,允许在数据库中
空白=True,允许在表单验证中

