Django Model的外键自关联
在django的model定义中,有时需要某个Field引用当前定义的Model,比如一个部门(Department)的Model,它有一个字段是上级部门(super_department),上级部门应该是一个外键并引用Model Department,即:
1
2
3
4
5
6
|
class Department(models.Model):
'''
some other filed
'''
super_department = models.ForeignKey(Department)
|
但是这样的定义对于python来说是不允许的,因为在定义Field super_department时,Department定义还未完成,python会提示你Department未定义,那么怎么办呢?放心吧,django已经为你考虑好这种情况了,只需要在定义时将ForeignKey所引用的Model改为‘self'即可,即:
1
2
3
4
5
6
|
class Department(models.Model):
'''
some other filed
'''
super_department = models.ForeignKey( 'self' )
|
然后同步models至数据库时就会生成一个引用自己的外键。
Django Model之引用一个未定义的Model
有时在django的Model定义中,会出现引用一个未定义Model的情况,比如一个用户(User)属于某一个部门(Department),每一个部门有一个领导(leader),这个领导也是一个用户,即:
1
2
3
4
5
6
7
8
9
|
class Department(models.Model):
name = models.CharField(max_length = 20 )
leader = models.ForeignKey(User, related_name = 'lead_group' , null = True )
class User(models.Model):
username = models.CharField(max_length = 20 )
department = models.ForeignKey(Department, related_name = 'users' )
|
但这么定义就会引发在Department定义时,Field leader引用User,但此时的User还未定义。有人会说,先定义User,再定义Department,那也会引发一样的问题,因为User的department引用Department,此时的Department一样未被定义。那么这时候怎么办呢?其实,只需要将ForeignKey引用的Model改为字符串即可,即:
1
2
3
4
5
6
7
8
9
|
class Department(models.Model):
name = models.CharField(max_length = 20 )
leader = models.ForeignKey( 'User' , related_name = 'lead_group' ) #User now be str type
class User(models.Model):
username = models.CharField(max_length = 20 )
department = models.ForeignKey(Department, related_name = 'users' )
|
以上这篇Django之Mode的外键自关联和引用未定义的Model方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/ranyixu11/article/details/76381631