当数据不为空时,由于空约束而无法保存数据

时间:2018-12-22 09:17:15

标签: python django

我在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).

我不明白为什么会这样。保存数据之前我的打印显示该部分不为空。但这似乎是我得到的错误

1 个答案:

答案 0 :(得分:2)

更改

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> section )。还有

Model.objects.get(someting=something)

返回一个对象。您分配

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

section = heading ,这意味着您尝试将对象分配给外键字段。 section 表示一个pk(int值),但获得了一个对象,因此它不会抛出null错误,因为它无法为不能为null的 section 分配有效值。

在您的代码中

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

标题获得单个对象。因此,您只需使用heading.pk即可获取对象pk值。