简体   繁体   English

django.db.utils.IntegrityError:NOT NULL 约束失败:unesco_site.category_id

[英]django.db.utils.IntegrityError: NOT NULL constraint failed: unesco_site.category_id

I am trying to populate database from data in the csv file using a python script.我正在尝试使用 python 脚本从 csv 文件中的数据填充数据库。 I did some research but couldn't find a relevant example rather I found python packages that would load csv.我做了一些研究,但找不到相关示例,而是找到了可以加载 csv 的 python 包。 And there some articles guiding on how to upload csv file which isn't what I wanted.还有一些关于如何上传 csv 文件的文章,这不是我想要的。

Following is a glimpse of load.csv file.以下是load.csv文件的一瞥。 There are 11 columns as you can see.如您所见,有 11 列。

# models.py
from django.db import models


class Category(models.Model):
    category = models.CharField(max_length=128)

    def __str__(self):
        return self.name

class State(models.Model):
    state = models.CharField(max_length=25)

    def __str__(self):
        return self.name


class Region(models.Model):
    region = models.CharField(max_length=25)

    def __str__(self):
        return self.region

class Iso(models.Model):
    iso = models.CharField(max_length=5)

    def __str__(self):
        return self.iso

class Site(models.Model):
    name = models.CharField(max_length=128)
    year = models.IntegerField(null=True)
    area = models.FloatField(null=True)
    describe = models.TextField(max_length=500)
    justify = models.TextField(max_length=500, null=True)
    longitude = models.TextField(max_length=25, null=True)
    latitude = models.TextField(max_length=25, null=True)

    #one to many field
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    state = models.ForeignKey(State, on_delete=models.CASCADE)
    region = models.ForeignKey(Region, on_delete=models.CASCADE)
    iso = models.ForeignKey(Iso, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

I'm not being able to make the relationship among the models while inserting data.我无法在插入数据时建立模型之间的关系。 Earlier, I had used get_or_create() method but I was recommended to not to use it as I had no default value to be given and used create() method.早些时候,我使用过get_or_create()方法,但建议我不要使用它,因为我没有提供default值并使用了create()方法。 Somewhere I had found that, until a data is saved Primary key isn't generated so, I tried saving data to the field each time after reading data but that also didn't work.在某处我发现,在保存数据之前不会生成主键,因此我每次在读取数据后都尝试将数据保存到字段中,但这也不起作用。 . . Following is the code in many_load.py script.以下是 many_load.py 脚本中的代码。 There's no problem in reading data.读取数据没有问题。

import csv 

#python3 manage.py runscript many_load

from unesco.models import Site, Category, Iso, Region, State

def run():
    fhand = open('unesco/load.csv')
    reader = csv.reader(fhand)
    next(reader)

    
    # Category.objects.all().delete()
    # Iso.objects.all().delete()
    # Region.objects.all().delete()
    # State.objects.all().delete()

    # Site.objects.all().delete()


    for row in reader:
        # print(row)
        # print (len(row))

        nm= Site.objects.create(name=row[0])
        dsc = Site.objects.create(describe=row[1])
        jst = Site.objects.create(justify=row[2])
        yr = Site.objects.create(year=row[3])
        lng = Site.objects.create(longitude=row[4])
        lat = Site.objects.create(latitude=row[5])
        area = Site.objects.create(area=row[6])

        
        st = Site(category=row[7], state=row[8], region=row[9], iso=row[10], 
                    name=nm, area=area, describe=dsc, justify=jst, longitude=lng, latitude=lat)
        st.save()

But when I try running the script python3 manage.py runscript many_load it gives me the following error.但是当我尝试运行脚本python3 manage.py runscript many_load它给了我以下错误。 Help please.请帮忙。 You could also refer me some good articles for understanding more on this.你也可以给我推荐一些很好的文章来了解更多。

Traceback (most recent call last):
  File "/home/bu113t/envs/djpro/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/bu113t/envs/djpro/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: unesco_site.category_id

This error is occurring because you are passing a string value to the category field of Site but it is expecting a Category object as it is a ForeignKey field.发生此错误是因为您将字符串值传递给Sitecategory字段,但它需要一个Category对象,因为它是一个ForeignKey字段。

Not only that you have other problems in many_load.py不仅你在many_load.py还有其他问题

The following code has the correction of all of the problems.以下代码修正了所有问题。 Hope it will work for you.希望它对你有用。

import csv

# python3 manage.py runscript many_load

from unesco.models import Site, Category, Iso, Region, State


def run():
    fhand = open('unesco/load.csv')
    reader = csv.reader(fhand)
    next(reader)

    # Category.objects.all().delete()
    # Iso.objects.all().delete()
    # Region.objects.all().delete()
    # State.objects.all().delete()

    # Site.objects.all().delete()

    for row in reader:
        # print(row)
        # print (len(row))

        nm = row[0]
        dsc = row[1]
        jst = row[2]
        yr = row[3]
        lng = row[4]
        lat = row[5]
        area = row[6]

        category = Category.objects.create(category=row[7])
        state = State.objects.create(state=row[8])
        region = Region.objects.create(region=row[9])
        iso = Iso.objects.create(iso=row[10])

        st = Site(category=category, state=state, region=region, iso=iso,
                  name=nm, area=area, describe=dsc, justify=jst, longitude=lng, latitude=lat)
        st.save()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Createsuperuser django.db.utils.IntegrityError: NOT NULL 约束失败 - Createsuperuser django.db.utils.IntegrityError: NOT NULL constraint failed django.db.utils.IntegrityError:NOT NULL约束失败 - django.db.utils.IntegrityError: NOT NULL constraint failed django.db.utils.IntegrityError: NOT NULL 约束失败: - django.db.utils.IntegrityError: NOT NULL constraint failed: django.db.utils.IntegrityError: NOT NULL 约束失败来自 Postman - django.db.utils.IntegrityError: NOT NULL constraint failed fom Postman django.db.utils.IntegrityError:UNIQUE约束失败:rango_page__new.category_id - django.db.utils.IntegrityError: UNIQUE constraint failed: rango_page__new.category_id django.db.utils.IntegrityError: NOT NULL 约束失败:user.id - django.db.utils.IntegrityError: NOT NULL constraint failed: user.id django.db.utils.IntegrityError:NOT NULL 约束失败:app.area_id - django.db.utils.IntegrityError: NOT NULL constraint failed: app.area_id django.db.utils.IntegrityError: NOT NULL 约束失败:new__inventory_app_item.accounting_class_id - django.db.utils.IntegrityError: NOT NULL constraint failed: new__inventory_app_item.accounting_class_id django.db.utils.IntegrityError:NOT NULL 约束失败:users_profile.user_id - django.db.utils.IntegrityError: NOT NULL constraint failed: users_profile.user_id django.db.utils.IntegrityError:NOT NULL 约束失败:home_post.author_id - django.db.utils.IntegrityError: NOT NULL constraint failed: home_post.author_id
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM