1. 程式人生 > >Django之Mode的外來鍵自關聯和引用未定義的Model

Django之Mode的外來鍵自關聯和引用未定義的Model

Django Model的外來鍵自關聯

在django的model定義中,有時需要某個Field引用當前定義的Model,比如一個部門(Department)的Model,它有一個欄位是上級部門(super_department),上級部門應該是一個外來鍵並引用Model Department,即:

class Department(models.Model):

    '''
    some other filed
    '''
    super_department = models.ForeignKey(Department)

但是這樣的定義對於python來說是不允許的,因為在定義Field super_department時,Department定義還未完成,python會提示你Department未定義,那麼怎麼辦呢?放心吧,django已經為你考慮好這種情況了,只需要在定義時將ForeignKey所引用的Model改為‘self’即可,即:

class Department(models.Model):
    
    '''
    some other filed
    '''
    super_department = models.ForeignKey('self')

然後同步models至資料庫時就會生成一個引用自己的外來鍵。

Django Model之引用一個未定義的Model

有時在django的Model定義中,會出現引用一個未定義Model的情況,比如一個使用者(User)屬於某一個部門(Department),每一個部門有一個領導(leader),這個領導也是一個使用者,即:

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改為字串即可,即:

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