简体   繁体   English

Django(或sqlite3)更改模型属性的顺序

[英]Django (or sqlite3) change(s) the sequence of attributes of a model

I'm using django with sqlite3, and here is my models.py : 我在sqlite3中使用django ,这是我的models.py

from django.db import models
from django.conf import settings
from django.utils import timezone

class VoterDetails(models.Model):
    number = models.CharField(max_length=200,null=True)
    voter_id = models.CharField(null=True,max_length=200)
    elector_name = models.CharField(max_length=200,null=True)
    father_or_husband_name = models.CharField(max_length=200,null=True)
    has_husband = models.CharField(max_length=200,null=True)
    house_no = models.CharField(max_length=200,null=True)
    age = models.CharField(max_length=200,null=True)
    sex = models.CharField(max_length=6,null=True)
    ac_name = models.CharField(max_length=200,null=True)
    parl_constituency = models.CharField(max_length=200,null=True)
    part_no = models.CharField(max_length=200,null=True)
    year = models.CharField(max_length=200,null=True)
    state = models.CharField(max_length=200,null=True)
    filename = models.CharField(max_length=200,null=True)
    main_town = models.CharField(max_length=200,null=True)
    police_station = models.CharField(max_length=200,null=True)
    mandal = models.CharField(max_length=200,null=True)
    revenue_division = models.CharField(max_length=200,null=True)   
    district = models.CharField(max_length=200,null=True)
    pin_code = models.CharField(max_length=200,null=True) 
    polling_station_name = models.CharField(max_length=200,null=True)
    polling_station_address = models.CharField(max_length=200,null=True)
    net_electors_male = models.CharField(max_length=200,null=True)
    net_electors_female = models.CharField(max_length=200,null=True) 
    net_electors_third_gender = models.CharField(max_length=200,null=True)
    net_electors_total = models.CharField(max_length=200,null=True)
    change = models.CharField(default="",max_length=200,null=True)

    def __str__(self):
        return self.elector_name

As one can see, there is no attribute, which would claim to be the primary key . 可以看到,没有属性可以声称是主键 In this case, django generates an attribute id , which is an auto incrementing Auto field , which is chosen as the primary key. 在这种情况下, django生成一个属性id ,它是一个自动递增的Auto field ,被选作主键。

I did the migrations, and then checked the schema of the table temp_voterdetails thus generated.( temp is the name of my app.) 我进行了迁移,然后检查了由此生成的表temp_voterdetails的模式。( temp是我的应用程序的名称。)

sqlite> .schema temp_voterdetails
CREATE TABLE IF NOT EXISTS "temp_voterdetails" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"age" varchar(200) NULL,
"ac_name" varchar(200) NULL,
"change" varchar(200) NULL,
"district" varchar(200) NULL, 
"elector_name" varchar(200) NULL, 
"father_or_husband_name" varchar(200) NULL, 
"filename" varchar(200) NULL, 
"has_husband" varchar(200) NULL, 
"main_town" varchar(200) NULL, 
"mandal" varchar(200) NULL, 
"net_electors_female" varchar(200) NULL, 
"net_electors_male" varchar(200) NULL, 
"net_electors_third_gender" varchar(200) NULL, 
"net_electors_total" varchar(200) NULL, 
"number" varchar(200) NULL, 
"pin_code" varchar(200) NULL, 
"police_station" varchar(200) NULL, 
"polling_station_address" varchar(200) NULL, 
"polling_station_name" varchar(200) NULL, 
"revenue_division" varchar(200) NULL, 
"sex" varchar(6) NULL, 
"state" varchar(200) NULL, 
"voter_id" varchar(200) NULL, 
"year" varchar(200) NULL, 
"house_no" varchar(200) NULL, 
"parl_constituency" varchar(200) NULL, 
"part_no" varchar(200) NULL);

As you can see, the order of attributes is alphabetical, and thus is changed from the original order of declaration of the attributes in the models.py file. 如您所见,属性的顺序是字母顺序的,因此已从models.py文件中属性声明的原始顺序更改了。

This thing aside, I tried to import a CSV (that followed the structure defined in the models.py file) by: 抛开这件事,我尝试通过以下方式导入CSV(遵循models.py文件中定义的结构):

.mode csv
.separator ","
.import /path/to/my/csv temp_voterdetails 

Then I get the error (times the number of rows, obviously): 然后我得到了错误(显然是乘以行数):

INSERT failed: UNIQUE constraint failed: temp_voterdetails.id
/path/to/my/csv:164705: expected 28 columns but found 27 - filling the rest with NULL

So, initially I thought that I'm not giving any input for the "id", so it must be auto generated, and thus should never fail the UNIQUE constraint. 因此,起初我以为我没有为“ id”提供任何输入,因此它必须是自动生成的,因此绝不能使UNIQUE约束失效。 But alas to the alphabetic shuffling of django to sqlite3 conversion, id seems to input from number , and at the end there is a single column left. 但是遗憾的是,从django到sqlite3的字母顺序转换,id似乎是从number输入的,最后只剩下一列。 Because of which the UNIQUE constraint fails, and the last column is left unused. 因此,UNIQUE约束失败,最后一列未使用。

How do I make sure that the schema of the table I create is correctly designed and is same as the model defined in models.py ? 如何确保我创建的表的架构设计正确并且与models.py定义的模型相同?


UPDATE: After the automatic alphabetical ordering of attributes is stopped, I'll add an attribute global_number (AUTO INCREMENT, primary key) just at the end. 更新:停止自动按字母顺序排列的属性顺序后,我将在最后添加一个属性global_number (AUTO INCREMENT,主键)。 All the other attributes might be matched with the 27 existing column headers, and the last one, since isn't present in the CSV file, will be generated automatically, thus generating my primary key. 所有其他属性都可能与现有的27个列标题匹配,并且最后一个属性(由于CSV文件中不存在)将自动生成,从而生成我的主键。

This is what I plan. 这是我的计划。 Correct me if this is wrong in any way. 如果这有任何错误,请纠正我。


The attributes seem to always be ordered alphabetically, in the sqlite3 model, because of which we can't directly import our csv using sqlite3. 在sqlite3模型中,属性似乎总是​​按字母顺序排列,因此,我们无法使用sqlite3直接导入csv。 The main problem I faced was the slow speed of row addition to the table. 我面临的主要问题是向表中添加行的速度较慢。 This was because I was doing 1 query per row addition. 这是因为我在每行添加中执行1个查询。 This can be easily solved by making a list of entry objects and bulk adding this to the table. 通过制作条目对象列表并将其批量添加到表中,可以轻松解决此问题。 This takes only a single query, thus takes considerably less time. 这仅需要单个查询,因此花费的时间要少得多。 Here is the code: 这是代码:

import os
import django
os.environ['DJANGO_SETTINGS_MODULE']='<your-site>.settings'
django.setup()
from temp.models import <your-model>
import csv
with open('/path/to/csvfile','r') as f:
    reader = csv.reader(f)
    lst = []
    for i,row in enumerate(reader):
        print('Adding :'+str(i))
        if(i!=0):
            lst.append(<your-model>(
                name = row[0], #attribute 1
                popularity = row[1], #attribute 2
                ssum = row[2], # attribute 3
                yearrange = row[3], #attribute 4
                state = row[4] # attribute 5
                ))
    <your-model>.objects.bulk_create(lst)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM