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

การสร้าง Pickle Field ใน Django Models


Pickle ใน Python ใช้ serialize และ deserialize โครงสร้างออบเจกต์ Python แปลงออบเจกต์เป็น byte stream เพื่อเก็บในไฟล์/ฐานข้อมูล รักษาสถานะโปรแกรมข้ามเซสชัน หรือส่งข้อมูลผ่านเครือข่าย

บทความนี้สอนสร้าง Django Field ที่เก็บ Pickle Objects ทำงานกับ models.py และ Django Shell เท่านั้น

ตัวอย่าง

ติดตั้ง django-picklefield:

pip install django-picklefield

ใน models.py:

from django.db import models
from picklefield.fields import PickledObjectField

class new_model(models.Model):
    args = PickledObjectField()

สร้างโมเดลพร้อม Pickle Field

ทดสอบใน Terminal รัน python manage.py shell:

from myapp.models import *
obj = new_model(args=['fancy', {'objects': 'inside'}]).save()
new_model.objects.all()

รัน shell สร้าง instance ที่เก็บ pickle objects ได้

บันทึกใน views:

from django.http import HttpResponse
def my_view(request):
    Object = new_model(args=['fancy', {'name': 'ath'}])
    Object.save()
    return HttpResponse("Object saved")

เก็บออบเจกต์ที่ pickle ได้ใดๆ ในฟิลด์นี้

เอาต์พุท

In [4]: new_model.objects.all()
Out[4]: <QuerySet [<new_model: new_model object (1)>]>