Django自引外键 [英] Django self-referential foreign key

查看:137
本文介绍了Django自引外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很喜欢webapps和数据库的东西,所以这可能是一个愚蠢的问题。我想用一个字段来指定一个模型(CategoryModel),该字段指向模型的另一个实例(其父级)的主要ID。

 code> class CategoryModel(models.Model):
parentId = models.ForeignKey(CategoryModel)

我该怎么做?谢谢!

解决方案

您可以将模型的名称作为字符串传递给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")

这篇关于Django自引外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆