问题: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


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。