且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django自引外键

更新时间:2023-02-02 23:02:54

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

所以:

  parentId = models.ForeignKey(CategoryModel)

或者您可以使用字符串self

  parentId = models.ForeignKey(self)


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!

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