IntegrityError: null value in column “city_id ” violates not-null constraint

你。 提交于 2019-12-19 06:03:11

问题


I two model:

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)

when I syncdb and create admin user :

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

How I can Fix this error?


回答1:


city = models.OneToOneField(City)

Are you sure you want only one user per city? I think you need

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

null, blank because the sycndb will create a profile and will fail if no city is passed.

Alternatively, you can pass default=default_city_id to the city ForeignKey



来源:https://stackoverflow.com/questions/16603657/integrityerror-null-value-in-column-city-id-violates-not-null-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!