gpt4 book ai didi

python - 当数据不为空时,由于空约束,保存数据失败

转载 作者:行者123 更新时间:2023-12-01 01:20:27 24 4
gpt4 key购买 nike

我在 django 中有以下 python 代码,该代码部署在 heroku 上:

def newimportdb(request):
import xlrd
loc = ("./CGHS Rates 2014- Trivandrum.xlsx")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
for i in range(sheet.nrows):
try:
sl = int(sheet.cell_value(i, 0))
except:
title = sheet.cell_value(i, 1)
hd = CGHSSection(title = title)
try:
hd.save()
heading = CGHSSection.objects.get(title = title)
print(f"Saved new heading: {title}")
continue
except:
print(f"Could not save new section: {title}. Maybe it existing. Reading it.")
heading = CGHSSection.objects.get(title = title)
continue

test = sheet.cell_value(i, 1)
nonnabh = int(sheet.cell_value(i, 2))
nabh = int(sheet.cell_value(i, 3))
print(f'{i} Test:{test} NonNABH:{nonnabh} NABH:{nabh} Under:{heading}')

it = CGHSRates(serial = sl, name =test, NABHrate = nabh, NonNrate=nonnabh, section=heading)
print(f"Value of section heading is {heading.title}")
print(f'it = CGHSRates(serial = {sl}, name ={test}, NABHrate = {nabh}, NonNrate={nonnabh}, section={heading}')
it.save()
print("Saved")

在我的模型中,我有:

from django.db import models
class CGHSRates(models.Model):
rid = models.AutoField(primary_key=True)
serial = models.IntegerField(default=0)
name = models.CharField(max_length=100)
NonNrate = models.FloatField(blank=True)
NABHrate = models.FloatField(blank=True)
section = models.ForeignKey('CGHSSection', on_delete=models.SET_NULL, null=True, blank=True)

class Meta:
unique_together = ('name', 'NonNrate', 'NABHrate')

class CGHSSection(models.Model):
num = models.AutoField(primary_key=True)
title = models.CharField(max_length=150, unique=True)

运行上面的代码后,我得到:

[22/Dec/2018 09:07:55] "GET /favicon.ico/ HTTP/1.1" 404 3346
Could not save new section: UNCLASSIFIED. Maybe it existing. Reading it.
1 Test:Consultation OPD NonNABH:135 NABH:135 Under:CGHSSection object (1)
Value of section heading is UNCLASSIFIED
it = CGHSRates(serial = 1, name =Consultation OPD, NABHrate = 135, NonNrate=135, section=CGHSSection object (1)
Internal Server Error: /app/import
Traceback (most recent call last):
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.IntegrityError: null value in column "section" violates not-null constraint
DETAIL: Failing row contains (3, 1, Consultation OPD, 135, 135, null, 1).


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/joel/peroorkada/app/views.py", line 134, in newimportdb
it.save()
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/db/models/base.py", line 718, in save
force_update=force_update, update_fields=update_fields)
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/db/models/base.py", line 748, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/db/models/base.py", line 831, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/db/models/base.py", line 869, in _do_insert
using=using, raw=raw)
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/db/models/query.py", line 1136, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1289, in execute_sql
cursor.execute(sql, params)
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/joel/sampledjango/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: null value in column "section" violates not-null constraint
DETAIL: Failing row contains (3, 1, Consultation OPD, 135, 135, null, 1).

我不明白为什么会发生这种情况。我在保存数据之前的打印显示该部分不为空。但这似乎是我遇到的错误

最佳答案

改变

it = CGHSRates(serial=sl, name=test, NABHrate=nabh, NonNrate=nonnabh, section=heading)

it = CGHSRates(serial=sl, name=test, NABHrate=nabh, NonNrate=nonnabh, section=heading.pk)

对于外键字段,它与pk(整数值)有关,因此您需要为外键分配一个pk(整数值)(在您的情况下:< em>部分)。并且

Model.objects.get(someting=something)

返回一个对象。您分配

it = CGHSRates(serial=sl, name=test, NABHrate=nabh, NonNrate=nonnabh, section=heading)

section=heading 这意味着您尝试将对象分配给外键字段。 section 方面 a pk(int value) 但获取一个对象,因此它会抛出非空错误,因为它无法为不可为空的 section 分配有效值。

在你的代码中

heading = CGHSSection.objects.get(title = title)

标题获取单个对象。所以你可以只使用heading.pk来获取对象pk值。

关于python - 当数据不为空时,由于空约束,保存数据失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53894426/

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