csv 데이터를 django 모델로 가져 오는 방법
CSV 데이터가 있고 예제 CSV 데이터를 사용하여 django 모델로 가져오고 싶습니다.
1;"02-01-101101";"Worm Gear HRF 50";"Ratio 1 : 10";"input shaft, output shaft, direction A, color dark green";
2;"02-01-101102";"Worm Gear HRF 50";"Ratio 1 : 20";"input shaft, output shaft, direction A, color dark green";
3;"02-01-101103";"Worm Gear HRF 50";"Ratio 1 : 30";"input shaft, output shaft, direction A, color dark green";
4;"02-01-101104";"Worm Gear HRF 50";"Ratio 1 : 40";"input shaft, output shaft, direction A, color dark green";
5;"02-01-101105";"Worm Gear HRF 50";"Ratio 1 : 50";"input shaft, output shaft, direction A, color dark green";
Product라는 django 모델이 있습니다. 제품에는 name
, description
및 같은 일부 필드가 있습니다 price
. 나는 다음과 같은 것을 원한다.
product=Product()
product.name = "Worm Gear HRF 70(02-01-101116)"
product.description = "input shaft, output shaft, direction A, color dark green"
product.price = 100
파이썬 언어의 일부인 csv 모듈을 사용하고 싶다면 Django의 get_or_create 메소드를 사용해야합니다.
with open(path) as f:
reader = csv.reader(f)
for row in reader:
_, created = Teacher.objects.get_or_create(
first_name=row[0],
last_name=row[1],
middle_name=row[2],
)
# creates a tuple of the new object or
# current object and a boolean of if it was created
내 예에서 모델 교사는 first_name, last_name 및 middle_name 세 가지 속성을 가지고 있습니다.
get_or_create 메소드 의 Django 문서
당신이 라이브러리를 사용하려는 경우, 빠른 구글 검색 csv
및 django
- 두 라이브러리 밝혀 장고 - csvimport 와 장고 - 어댑터를 . 그들이 자신에 대해 무엇을 말해야하는지 읽어 보자 ...
- 장고 어댑터 :
Django 어댑터는 CSV / XML 파일을 python 객체 또는 django 모델 인스턴스로 쉽게 변환 할 수있는 도구입니다.
- django-importcsv :
django-csvimport는 데이터를 채우기 위해 CSV 파일을 업로드 할 수있는 일반 가져 오기 도구입니다.
첫 번째는 csv 파일과 일치하는 모델을 작성해야하는 반면 두 번째는 명령 줄 임포터에 가깝습니다. 이는 작업 방식에 큰 차이 가 있으며 각각 다른 유형의 프로젝트에 적합합니다.
그래서 어느 것을 사용할까요? 이는 장기적으로 프로젝트에 더 적합한 옵션에 따라 다릅니다.
그러나 (경고, 의사 코드 앞) 다음 행을 따라 csv 파일을 가져 오는 자체 django 스크립트 를 작성하여 라이브러리를 모두 피할 수도 있습니다 .
# open file & create csvreader
import csv, yada yada yada
# import the relevant model
from myproject.models import Foo
#loop:
for line in csv file:
line = parse line to a list
# add some custom validation\parsing for some of the fields
foo = Foo(fieldname1=line[1], fieldname2=line[2] ... etc. )
try:
foo.save()
except:
# if the're a problem anywhere, you wanna know about it
print "there was a problem with line", i
아주 쉽습니다. 일회성 가져 오기라면 장고 쉘을 통해 대화식으로 할 수 있습니다. 프로젝트로 무엇을하고 싶은지, 얼마나 많은 파일을 처리해야하는지 파악한 다음, 라이브러리를 사용하기로 결정한 경우 어떤 것이 필요에 더 잘 맞는지 찾아보십시오 .
Python csv 라이브러리 는 구문 분석을 수행 할 수 있으며 코드는이를 Products()
.
django-adaptors를 사용할 수도 있습니다.
>>> from adaptor.model import CsvModel
>>> class MyCSvModel(CsvModel):
... name = CharField()
... age = IntegerField()
... length = FloatField()
...
... class Meta:
... delimiter = ";"
다음과 같이 CSV 파일과 일치하는 MyCsvModel을 선언합니다.
안토니; 27; 1.75
파일 또는 반복 가능한 객체를 가져 오려면 다음을 수행하십시오.
>>> my_csv_list = MyCsvModel.import_data(data = open("my_csv_file_name.csv"))
>>> first_line = my_csv_list[0]
>>> first_line.age
27
명시 적 선언이 없으면 데이터와 열이 동일한 순서로 일치됩니다.
Anthony --> Column 0 --> Field 0 --> name
27 --> Column 1 --> Field 1 --> age
1.75 --> Column 2 --> Field 2 --> length
이 같은:
f = open('data.txt', 'r')
for line in f:
line = line.split(';')
product = Product()
product.name = line[2] + '(' + line[1] + ')'
product.description = line[4]
product.price = '' #data is missing from file
product.save()
f.close()
내가 사용하는 django 1.8의 경우,
앞으로 동적으로 객체를 생성 할 수있는 명령을 만들었 기 때문에 csv의 파일 경로, 관련 장고 애플리케이션의 모델 이름, 앱 이름 만 입력하면 해당 필드를 지정하지 않고 해당 모델을 채울 수 있습니다. 이름. 예를 들어 다음 csv를 사용하면 :
field1,field2,field3
value1,value2,value3
value11,value22,value33
명령에 입력 할 모델 이름에 대한 개체 [{field1 : value1, field2 : value2, field3 : value3}, {field1 : value11, field2 : value22, field3 : value33}]를 만듭니다.
명령 코드 :
from django.core.management.base import BaseCommand
from django.db.models.loading import get_model
import csv
class Command(BaseCommand):
help = 'Creating model objects according the file path specified'
def add_arguments(self, parser):
parser.add_argument('--path', type=str, help="file path")
parser.add_argument('--model_name', type=str, help="model name")
parser.add_argument('--app_name', type=str, help="django app name that the model is connected to")
def handle(self, *args, **options):
file_path = options['path']
_model = get_model(options['app_name'], options['model_name'])
with open(file_path, 'rb') as csv_file:
reader = csv.reader(csv_file, delimiter=',', quotechar='|')
header = reader.next()
for row in reader:
_object_dict = {key: value for key, value in zip(header, row)}
_model.objects.create(**_object_dict)
아마도 이후 버전에서는
from django.db.models.loading import get_model
더 이상 사용되지 않으며 다음으로 변경해야합니다.
from django.apps.apps import get_model
django-csv-importer 패키지를 사용할 수 있습니다. http://pypi.python.org/pypi/django-csv-importer/0.1.1
장고 모델처럼 작동합니다.
MyCsvModel(CsvModel):
field1 = IntegerField()
field2 = CharField()
etc
class Meta:
delimiter = ";"
dbModel = Product
그리고 다음을 수행해야합니다. CsvModel.import_from_file ( "my file")
그러면 자동으로 제품이 생성됩니다.
Use the Pandas library to create a dataframe of the csv data.
Name the fields either by including them in the csv file's first line or in code by using the dataframe's columns method.
Then create a list of model instances.
Finally use the django method .bulk_create() to send your list of model instances to the database table.
The read_csv function in pandas is great for reading csv files and gives you lots of parameters to skip lines, omit fields, etc.
import pandas as pd
tmp_data=pd.read_csv('file.csv',sep=';')
#ensure fields are named~ID,Product_ID,Name,Ratio,Description
#concatenate name and Product_id to make a new field a la Dr.Dee's answer
products = [
Product(
name = tmp_data.ix[row]['Name']
description = tmp_data.ix[row]['Description'],
price = tmp_data.ix[row]['price'],
)
for row in tmp_data['ID']
]
Product.objects.bulk_create(products)
I was using the answer by mmrs151 but saving each row (instance) was very slow and any fields containing the delimiting character (even inside of quotes) were not handled by the open() -- line.split(';') method.
Pandas has so many useful caveats, it is worth getting to know
If you're working with new versions of Django (>10) and don't want to spend time writing the model definition. you can use the ogrinspect tool.
This will create a code definition for the model .
python manage.py ogrinspect [/path/to/thecsv] Product
The output will be the class (model) definition. In this case the model will be called Product. You need to copy this code into your models.py file.
Afterwards you need to migrate (in the shell) the new Product table with:
python manage.py makemigrations
python manage.py migrate
More information here: https://docs.djangoproject.com/en/1.11/ref/contrib/gis/tutorial/
Do note that the example has been done for ESRI Shapefiles but it works pretty good with standard CSV files as well.
For ingesting your data (in CSV format) you can use pandas.
import pandas as pd
your_dataframe = pd.read_csv(path_to_csv)
# Make a row iterator (this will go row by row)
iter_data = your_dataframe.iterrows()
Now, every row needs to be transformed into a dictionary and use this dict for instantiating your model (in this case, Product())
# python 2.x
map(lambda (i,data) : Product.objects.create(**dict(data)),iter_data
Done, check your database now.
Here's a django egg for it:
Consider using Django's built-in deserializers. Django's docs are well-written and can help you get started. Consider converting your data from csv to XML or JSON and using a deserializer to import the data. If you're doing this from the command line (rather than through a web request), the loaddata
manage.py command will be especially helpful.
You can give a try to django-import-export. It has nice admin integration, changes preview, can create, update, delete objects.
define class in models.py and a function in it.
class all_products(models.Model):
def get_all_products():
items = []
with open('EXACT FILE PATH OF YOUR CSV FILE','r') as fp:
# You can also put the relative path of csv file
# with respect to the manage.py file
reader1 = csv.reader(fp, delimiter=';')
for value in reader1:
items.append(value)
return items
You can access ith element in the list as items[i]
참고 URL : https://stackoverflow.com/questions/2459979/how-to-import-csv-data-into-django-models
'IT TIP' 카테고리의 다른 글
Node.js의 S3 getObject에서 응답을 얻는 방법은 무엇입니까? (0) | 2020.12.10 |
---|---|
JavaScript에서! =는! ==와 동일합니다. (0) | 2020.12.10 |
IE 8에서 JSON.stringify ()를 지원합니까? (0) | 2020.12.10 |
MemoryStream.Close () 또는 MemoryStream.Dispose () (0) | 2020.12.10 |
복합 디자인 패턴은 언제 사용해야합니까? (0) | 2020.12.10 |