01_django_SQliteDB 파일 입출력


http://127.0.0.1:8000/admin/

csv 파일을 읽어서 Sqlite DB에 저장하는 과정


matdbs를 누르면 위의 창에 있음


-------------------------------------------------------------------------------------------

 # ref. https://itwithruilan.tistory.com/69

1. $ pip install django-import-export

2. Setting.py에서 

INSTALLED_APPS = (
    ...
    'import_export',
)

3. $ python manage.py collectstatic

👉🏻collectstatic은 서버에 배포할 때 여러 앱별로 흩어져 있는 static 파일을 한 곳으로 
모아주기 위해 쓰는 명령어이다. 

// 실제로 작동하지 않음


4. models.py

#models.py
class Store(models.Model):
	name = models.CharField(max_length=70)
	location = models.CharField(max_length=140, null=True, blank=True)
	number = models.CharField(max_length=80, null=True, blank=True)

5. admin.py

#admin.py
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from .models import Store

class StoreResource(resources.ModelResource):
	class Meta:
		model = Store
		fields = ('id', 'name', 'location', 'number')
		export_order = fields


class StoreAdmin(ImportExportModelAdmin)
	fields = ('name', 'location', 'number')
	list_display = ('id', 'name', 'location', 'number')
	resource_class = StoreResource


admin.site.register(Store, StoreAdmin)

👉🏻db를 admin 페이지를 통해 넣기 때문에 admin.py에서 코드를 짜야한다. 총 2개의 class가 필요하다.

✍🏻StoreResource: 클래스 이름 그대로 db에 넣을 자료에 대해 정의한다.

  • model: 어떤 모델에 대한 자료인지 정의한다. → 나는 Store 모델!
  • fields: 어떤 필드를 넣을 지 정의한다. → 나는 모델의 모든 필드를 넣음
  • export_order: export할 때 어떠한 순서로 자료를 내보낼 지 정의한다.

✍🏻StoreAdmin: admin 페이지에서 어떻게 보일지 정의한다.

  • fields: admin에서 정보 상세 정보 페이지에 들어가면 보일 필드를 정의한다. 여기에서는 수정 가능한 필드만 적을 수 있다. (id나 created_at과 같은 필드는 수정할 수 없으므로 적을 수 없다.)
  • list_display: admin에서 해당 모델에 들어가면 보일 필드를 정의한다. 
  • resource_class: db에 넣을 자료에 대해 정의한 클래스를 지정한다.

✍🏻마지막으로 admin에 register하면 된다.


6. DB update

python manage.py makemigrations
python manage.py migrate


(TBRVT) C:\inetpub\TBRVT\web01\pjt01\web01\web01>python manage.py makemigrations

Migrations for 'app01':

  app01\migrations\0011_remove_matdb_structure_check_alter_matdb_epi_and_more.py

    - Remove field structure_check from matdb

    - Alter field EPI on matdb

    - Alter field Ga on matdb

    - Alter field bendingStiffness on matdb

    - Alter field code_T2 on matdb

    - Alter field factory on matdb

    - Alter field matCode on matdb

    - Alter field rubber on matdb

    - Alter field section on matdb

    - Alter field strength_measure on matdb

    - Alter field strength_spec on matdb

    - Alter field structure on matdb


(TBRVT) C:\inetpub\TBRVT\web01\pjt01\web01\web01>python manage.py migrate

Operations to perform:

  Apply all migrations: admin, app01, auth, contenttypes, sessions

Running migrations:

  Applying app01.0011_remove_matdb_structure_check_alter_matdb_epi_and_more... OK


mat파일은 google sheet에 있음
최종파일


Ref.1) 원본의 인덱스 이름과 models.py의 열이름이 같아야 한다.
Ref.2) 데이터 필드의 형이 일치되어야 한다. 












댓글

이 블로그의 인기 게시물

abaqus gpu 사용

Chat GPI 활용

코어와 쓰레드 개념