gpt4 book ai didi

sql - django.db.utils.IntegrityError : column "venue_city" contains null values 错误

转载 作者:行者123 更新时间:2023-11-29 11:16:49 33 4
gpt4 key购买 nike

我已经在 stackoverflow 和谷歌上阅读了很多其他帖子,但我找不到解决方案。

这一切都始于我将模型从 CharField 更改为 ForeignKey。我收到的错误是:

Operations to perform:
Synchronize unmigrated apps: gis, staticfiles, crispy_forms, geoposition, messages
Apply all migrations: venues, images, amenities, cities_light, registration, auth, admin, sites, sessions, contenttypes, easy_thumbnails, newsletter
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying venues.0016_auto_20160514_2141...Traceback (most recent call last):
File "/Users/iam-tony/.envs/venuepark/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.IntegrityError: column "venue_city" contains null values

我的模型如下:

class Venue(models.Model):
venue_city = models.ForeignKey(City, null=True,)
venue_country=models.ForeignKey(Country, null=True)

venue_country 之前不存在,因此迁移成功。但是 venue_city 是一个 CharField。

我对我的迁移文件进行了一些更改,以便它可以按如下方式执行 sql:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('venues', '0011_venue_map_activation'),
]

migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city TYPE integer USING venue_city::integer '''),

migrations.RunSQL(''' ALTER TABLE venues_venue ALTER venue_city RENAME COLUMN venue_city TO venue_city_id '''),

migrations.RunSQL(''' ALTER TABLE venues_venue ADD CONSTRAINT venues_venus_somefk FOREIGN KEY (venue_city_id) REFERENCES cities_light (id) DEFERRABLE INITIALLY DEFERRED'''),

提前致谢!

更新:我的新迁移文件:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('cities_light', '0006_compensate_for_0003_bytestring_bug'),
('venues', '0024_remove_venue_venue_city'),
]

operations = [
migrations.AddField(
model_name='venue',
name='venue_city',
field=models.ForeignKey(null=True, to='cities_light.City'),
),
]

最佳答案

看起来您在创建迁移文件后添加了 null=True。因为 venue_city 在您的迁移文件中不是可为空的字段

按照以下步骤操作。

1) Drop venue_city & venue_country from your local table
3) Delete all the migration files you created for these `CharField to a ForeignKey` change
4) execute `python manage.py makemigrations`
5) execute 'python manage.py migrate'

它应该工作

关于sql - django.db.utils.IntegrityError : column "venue_city" contains null values 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37241819/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com