Detailed Explanation of Python django Derived excel
- 2021-12-11 18:39:00
- OfStack
Directory 1. Basic environment 2. Requirements 3. Function realization 4. Source code 1. Sequential class realization 2. Manual conversion foreign key realization summary
django restframework Import excel content, you can view another article
1. Basic environment
web architecture: The front and back ends are separated, the front end uses vue, and the back end uses rest framework of django
django Version 3.2
django-excel version 0.0. 10
djangorestframework version 3.12. 4
2. Requirements
Export excel data content from interface
Import model contains foreign key types
3. Function realization
1. Do not use serialization classes: You need to manually convert foreign key objects to foreign key values
2. Use ordered classes:
4. Source code
#models.py
from django.db import models
from django.utils import timezone
class MyITtype(models.Model):
name = models.CharField(verbose_name=" Name ", max_length=128, unique=True)
ittype = models.SmallIntegerField(verbose_name=" Type ")
comment = models.TextField(verbose_name=" Remarks ", blank=True, default="")
def __str__(self):
return self.name
class Meta:
db_table = "MyITtype"
verbose_name = "it Type of asset "
class MyAsset(models.Model):
ittype = models.ForeignKey(MyITtype, on_delete=models.SET_NULL, verbose_name=" Product type ", null=True)
code = models.CharField(verbose_name=" Asset code ", max_length=128, unique=True)
buytime = models.DateField(verbose_name=" Warehouse time ", default=timezone.now)
usetime = models.DateField(verbose_name=" Allocate time ", default=timezone.now)
comment = models.TextField(verbose_name=" Specification ", blank=True, default="")
user = models.CharField(verbose_name=" User ", max_length=128, blank=True, default="")
status = models.IntegerField(verbose_name=" Status ")
def __str__(self):
return self.code
class Meta:
db_table = "opGTITAsset"
verbose_name = "it Fixed production "
1. Ordered class implementation
#asset-export.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.serializers import ModelSerializer
from .models import MyAsset
import django_excel as excel
class ITAssetSer(ModelSerializer):
class Meta:
model = MyAsset
fields = '__all__'
class ITAssetExport(APIView):
""""""
use_model = MyAsset
queryset = use_model.objects.all()
serializer_class = ITAssetSer
def post(self, request, *args, **kwargs):
try:
data = request.data
id_list = data.get("data")
obj_list = self.queryset.all()
# If there is a value, it means exporting part, otherwise it exports all
if id_list:
obj_list = obj_list.filter(id__in=id_list)
ser = self.serializer_class(instance=obj_list, many=True)
return MakeExcel(obj_list=ser.data, class_name=self.use_model, filename="itasset")
except:
ret = {
"code": 599,
"message": " Error exporting data "
}
return Response(ret)
def get(self, request, *args, **kwargs):
self.http_method_not_allowed(request, *args, **kwargs)
def MakeExcel(obj_list, class_name, filename):
"""
Production excel Table
:param ser_list: Content list
:param class_name: Class name
:param filename: Filename
:return:
"""
meta_fields = class_name._meta.fields
name_list = [field.name for field in meta_fields]
header_list = [field.verbose_name for field in meta_fields]
wdata = [header_list]
for obj in obj_list:
data = [obj[name] for name in name_list]
wdata.append(data)
sheet = excel.pe.Sheet(wdata)
response = excel.make_response(pyexcel_instance=sheet, file_name=filename, file_type="xlsx")
return response
2. Manually convert the foreign key implementation
#asset-export.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.objializers import ModelSerializer
from .models import MyAsset
import django_excel as excel
class ITAssetSer(ModelSerializer):
class Meta:
model = MyAsset
fields = '__all__'
class ITAssetExport(APIView):
""""""
use_model = MyAsset
queryset = use_model.objects.all()
objializer_class = ITAssetSer
def post(self, request, *args, **kwargs):
try:
obj_list = self.use_model.objects.all()
return MakeExcel(obj_list=obj_list, class_name=self.use_model, filename="itasset")
except:
ret = {
"code": 599,
"message": " Error exporting data "
}
return Response(ret)
def get(self, request, *args, **kwargs):
self.http_method_not_allowed(request, *args, **kwargs)
def MakeExcel(obj_list, class_name, filename):
"""
Production excel Table
:param obj_list: Content list
:param class_name: Class name
:param filename: Filename
:return:
"""
meta_fields = class_name._meta.fields
name_list = [field.name for field in meta_fields]
header_list = [field.verbose_name for field in meta_fields]
wdata = [header_list]
for obj in obj_list:
data = []
for name in name_list:
value = eval("obj." + name) # Equivalent to getattr(obj,name) That is, get the contents of a field of the object
if isinstance(value, Model):
value = eval("".join(["obj." + name + "_id"])) # Equivalent to obj.name_id That is, get the value of the foreign key object in the object
data.append(value)
# Reference example
# data = [getattr(obj, name) if name != "ittype" else obj.ittype_id for name in name_list]
wdata.append(data)
sheet = excel.pe.Sheet(wdata)
response = excel.make_response(pyexcel_instance=sheet, file_name=filename, file_type="xlsx")
return response
Summarize
This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!