首页 > 解决方案 > 使用 pandas 将数据加载到 Django SQLite 中导致异常值:外键不匹配

问题描述

在这种情况下,对于 Django 模型,我不能使用 pandas 将数据放入 sqlite(SQL) 中吗?

我想用pandas做一些数据清理和数据合并,然后放到SQL中。在做熊猫之前,我创建了我的 django 模型。

模型.py

# myapp
from django.db import models
from django.contrib.auth.models import User 

class Agency(models.Model):
    system_name = models.CharField(max_length=255)
    county = models.CharField(max_length=60)
    active = models.BooleanField(default=True)

    system_type_tuple = [('ED', 'School'),('PG','Power Generation'),('TF','Some other Facility'),('UN','Unknown')]
    system_type = models.CharField(max_length=2, choices=system_type_tuple, default= 'UN')
    zipcode = models.CharField(max_length=5, null=True, blank=True)
    agency_no = models.CharField(max_length=7, primary_key=True, unique=True)

    def __str__(self):
        return self.agency_no

class SitePart(models.Model):
    system_no = models.ForeignKey('Agency', on_delete=models.CASCADE, db_column='agency_no', null=True, blank=True,)
    part_name = models.CharField(max_length=125) 
    status_tuple = [('AB','Abandoned'),('AC','Active Compliant'),('DS','Destroyed'),('NP','Need Permit'),('SB','Stand By waiting acitvation')]
    status = models.CharField(max_length=2, choices=status_tuple, default= 'SB')

    sys_site_n = models.CharField(max_length=15, unique=True)

    def __str__(self):
        return self.part_name

要为上述模型创建 SQL 数据库,我在终端中输入以下命令:

我的 pandas_script.py 是这样的:

import pandas as pd
import sqlite3 as sql
import openpyxl
import numpy as np

conn = sql.connect('C:path_to/Django/my_project/db.sqlite3')
support_dir = "C:/.../support/"
file1 = support_dir + 'file1.xlsx'
file2 = support_dir + 'file2.xlsx'

df1 = pd.read_excel(open(file1, 'rb'), engine='openpyxl', sheet_name="Sheet1",  usecols = 'A,B,D:G')
df2 = pd.read_excel(open(file2, 'rb'), engine='openpyxl', sheet_name="Sheet1",  usecols = 'A,C,F')

# then there is splits, renaming, merging, replace nulls, filtering, change column names...

dfa.sort_values(by=['agency_no'], inplace=True)
print(dfa.head())
print(dfa.shape)
dfa.to_sql('myapp_agency', conn, index=False, if_exists='replace')

然后我运行服务器并导航到我的模型管理站点并尝试添加一个站点部分条目。单击保存时,我收到错误消息。

Traceback(最近一次调用最后一次):文件“C:\Users...\Python\Python39\lib\site-packages\django\db\backends\utils.py”,第 84 行,在 _execute 中返回 self.cursor.execute (sql, params) 文件“C:\Users...\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py”,第 413 行,执行返回 Database.Cursor.execute(自我,查询,参数)sqlite3.OperationalError:外键不匹配 - “myapp_sitepart”引用“myapp_agency”

标签: djangopandassqlite

解决方案


推荐阅读