Django自引用外键

问题:Django自引用外键

一般来说,我对Web应用程序和数据库内容还是陌生的,所以这可能是一个愚蠢的问题。我想制作一个模型(“ CategoryModel”),其字段指向模型的另一个实例(其父实例)的主要ID。

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

我该怎么做呢?谢谢!

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):
    parent = models.ForeignKey(CategoryModel)

How do I do this? Thanks!


回答 0

您可以将模型的名称作为字符串传递给ForeignKey,它将做正确的事情。

所以:

parent = models.ForeignKey("CategoryModel")

或者您可以使用字符串“ self”

parent = models.ForeignKey("self")

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

So:

parent = models.ForeignKey("CategoryModel")

Or you can use the string “self”

parent = models.ForeignKey("self")

回答 1

您可以使用字符串“ self”表示自我参考。

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

https://docs.djangoproject.com/zh-CN/dev/ref/models/fields/#foreignkey

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

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

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


回答 2

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

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

要么

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

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

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/


回答 3

您还要设置null = True和blank = True

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

null = True,允许在数据库中
blank = True,允许在表单中验证

You also to sett null=True and 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