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

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

问题描述

我对网络应用程序和数据库的东西一般都是新手,所以这可能是一个愚蠢的问题.我想创建一个模型(CategoryModel"),其字段指向模型的另一个实例(其父级)的主 ID.

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)

我该怎么做?谢谢!

推荐答案

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

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

所以:

parent = models.ForeignKey("CategoryModel")

或者你可以使用字符串self"

Or you can use the string "self"

parent = models.ForeignKey("self")

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

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