2013-05-17 136 views
7

我兩型:IntegrityError:列「city_id」空值違反非空約束

class City(models.Model): 
    name = models.CharField(max_length=50) 
    country = models.OneToOneField(Country) 

    def __unicode__(self): 
     return self.name 


class UserProfile(models.Model): 
    user = models.OneToOneField(User) 
    city = models.OneToOneField(City) 

當我執行syncdb並創建管理員用戶:

IntegrityError: null value in column "city_id" violates not-null constraint 

我怎麼能解決這個問題?

回答

8
city = models.OneToOneField(City) 

您確定每個城市只有一個用戶嗎?我認爲你需要

city = models.ForeignKey(City, null=True, blank=True) 

null, blank因爲sycndb將創建一個配置文件,如果沒有city傳遞將失敗。

或者,您也可以通過default=default_city_idcityForeignKey

相關問題