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

การติดตามประวัติออบเจกต์โมเดลใน Django


Model history tracking เป็นฟีเจอร์ที่ติดตามการเปลี่ยนแปลงของออบเจกต์โมเดล รวมถึงการลบ ช่วยกู้คืนออบเจกต์ที่ลบได้ บทความนี้สาธิตการติดตามประวัติโมเดลใน Django

ตัวอย่าง

ตั้งค่าโปรเจกต์ แอป urls และโมเดล

ติดตั้ง django-simple-history:

pip install django-simple-history

ใน settings.py:

INSTALLED_APPS+=["simple_history"]
MIDDLEWARE = [
    # middleware อื่นๆ
    'simple_history.middleware.HistoryRequestMiddleware',
]

เพิ่มโมดูลและ middleware

ใน models.py:

from django.db import models
from simple_history.models import HistoricalRecords

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

สร้างโมเดลและฟิลด์ history ที่บันทึกทุกการเปลี่ยนแปลง

ใน admin.py:

from django.contrib import admin
from .models import StudentData
from simple_history.admin import SimpleHistoryAdmin
admin.site.register(StudentData, SimpleHistoryAdmin)

ลงทะเบียนโมเดลกับ history tracking admin

รันคำสั่ง:

python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser

โค้ดใน models.py จะบันทึกข้อมูลประวัติทั้งหมด เข้าถึงได้ใน views.py หรือ Django shell

เอาต์พุต

การติดตามประวัติออบเจกต์โมเดลใน Django การติดตามประวัติออบเจกต์โมเดลใน Django การติดตามประวัติออบเจกต์โมเดลใน Django การติดตามประวัติออบเจกต์โมเดลใน Django