简体   繁体   English

Django自引用外键

[英]Django self-referential foreign key

I'm kind of new to webapps and database stuff in general so this might be a dumb question.我对 webapps 和数据库的东西一般都是新手,所以这可能是一个愚蠢的问题。 I want to make a model ("CategoryModel") with a field that points to the primary id of another instance of the model (its parent).我想制作一个模型(“CategoryModel”),其字段指向模型的另一个实例(其父级)的主 ID。

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

How do I do this?我该怎么做呢? Thanks!谢谢!

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")

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

You also to set null=True and blank=True您还可以设置null=Trueblank=True

class CategoryModel(models.Model):
    parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True)

null=True , to allow in database null=True ,允许在数据库中
blank=True , to allow in form validation blank=True ,允许表单验证

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/

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

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