在 Django 中,如何让模型引用自身? [英] In Django, how do you make a model refer to itself?

查看:31
本文介绍了在 Django 中,如何让模型引用自身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有 Employee 类.我想要一个引用同一类的不同实例的字段.

Assume we have class Employee. I want to have a field which references a different instance of the same class.

这个怎么写?下面的代码怎么样?

How to write this? How about the following code?

ref_employee= models.ForeignKey('self',null=True,blank=True)

推荐答案

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

创建递归关系——具有多对一的对象与自身的关系——使用models.ForeignKey('self').

To create a recursive relationship -- an object that has a many-to-one relationship with itself -- use models.ForeignKey('self').

所以你说得对.通常通过运行来确定代码是否可以执行您想要的操作会更快:)

So you have it right. It's usually faster to determine if code will do what you want by running it :)

这篇关于在 Django 中,如何让模型引用自身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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