Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การนำเข้าข้อมูล vào โมเดลใน Django


บทความนี้สอนนำเข้าข้อมูลจากรูปแบบ JSON เข้า model สามารถนำเข้าจาก json, csv, xlsx, yml ได้

สร้างโปรเจกต์และแอป ตั้งค่า urls เพิ่มแอปใน INSTALLED_APPS

สร้างโมเดล ทำงานกับ settings.py, admin.py, models.py และ admin urlpoint เท่านั้น

ตัวอย่าง

ติดตั้ง django-import-export:

pip install django-import-export

ใน settings.py:

INSTALLED_APPS += ['import_export']

สร้างโมเดล:

class StudentData(models.Model):
    name = models.CharField(max_length=100)
    standard = models.CharField(max_length=100)
    section = models.CharField(max_length=100)

ใน admin.py:

from django.contrib import admin
from .models import StudentData
from import_export import resources
from import_export.admin import ImportExportModelAdmin

class StudentResource(resources.ModelResource):
    class Meta:
        model = StudentData

class StudentAdmin(ImportExportModelAdmin):
    resource_class = StudentResource

admin.site.register(StudentData, StudentAdmin)

สร้าง ModelResource สำหรับ import/export แล้วลงทะเบียน Admin

รูปแบบไฟล์ JSON:

[
    {
        "id": 13,
        "name": "John",
        "standard": "10",
        "section": "B",
        "the_json": {"name": "Jhon"}
    }
]

สร้างไฟล์ import_example.json บน Notepad

เอาต์พุต

การนำเข้าข้อมูล vào โมเดลใน Django

นำเข้าไฟล์ JSON import_example.json ข้อมูลจะเข้าสู่โมเดล Django