模型类代码
from django.db import models
# Create your models here.
# 父类
class BaseModel(models.Model):
created_time = models.DateTimeField("创建时间", auto_now_add=True)
updated_time = models.DateTimeField("更新时间", auto_now=True)
# 部门模型类
class Department(BaseModel):
# 模型类插入数据时,只写类属性
name = models.CharField("部门", max_length=100)
def __str__(self):
return self.name
class Meta:
db_table = "department_tb"
# 职务模型类
class Duty(BaseModel):
name = models.CharField("职务名称", max_length=50)
def __str__(self):
return self.name
class Meta:
db_table = "duty_tb"
# 员工的模型类 不能同时继承BaseModel
class Staff(models.Model):
SEX = (
(1, "男"),
(2, "女")
)
name = models.CharField("姓名", max_length=20)
sex = models.IntegerField("性别", choices=SEX, default=1)
phone = models.CharField("手机号", max_length=11)
email = models.CharField("邮箱", max_length=20)
department = models.ForeignKey(to=Department, on_delete=models.CASCADE, verbose_name="部门")
duty = models.ForeignKey(to=Duty, on_delete=models.CASCADE, verbose_name="职责")
def __str__(self):
return self.name
class Meta:
db_table = "staff_tb"
序列化器 代码
from rest_framework import serializers
from .models import Department, Duty, Staff
class DepartmentSerializer(serializers.Serializer):
id = serializers.IntegerField(label="部门编号", read_only=True)
name = serializers.CharField(label="部门", max_length=100, min_length=3)
# 插入数据时,重写create方法
def create(self, validated_data):
return Department.objects.create(**validated_data)
# 更新数据时,重写update方法
def update(self, instance, validated_data):
instance.name = validated_data.get("name")
instance.save()
return instance
class DutySerializer(serializers.Serializer):
name = serializers.CharField(label="工作职责", max_length=50, min_length=20)
class StaffSerializer(serializers.Serializer):
SEX = (
(1, "男"),
(2, "女")
)
name = serializers.CharField(label="员工姓名", min_length=2, max_length=20)
sex = serializers.ChoiceField(choices=SEX, default=1, label="性别")
phone = serializers.CharField(max_length=11, label='手机号')
# 外键 反序列化时,指定queryset
# 序列化时,readonly=True
department = serializers.PrimaryKeyRelatedField(label='部门', queryset=Department.objects.all(), many=True, allow_null=True)
duty = serializers.PrimaryKeyRelatedField(label="职责", queryset=Duty.objects.all(), many=True, allow_null=True)
def create(self, validated_data):
name = validated_data.get("name")
sex = validated_data.get("sex")
phone = validated_data.get("phone")
dep_obj = validated_data.get("department")[0]
duty_obj = validated_data.get("duty")[0]
print("validated_data:", validated_data)
print("xxxx:", name, phone, dep_obj, duty_obj)
# 外键要给对象
return Staff.objects.create(name=name, sex=sex, phone=phone, department=dep_obj, duty=duty_obj)
# ModelSerializer
class DepartmentModelSerializer(serializers.ModelSerializer):
class Meta:
model = Department # 指定要序列化的模型类
fields = '__all__' # 指定要序列化的字段,__all__所有字段
class DutyModelSerializer(serializers.ModelSerializer):
class Meta:
model = Duty
fields = ("id","name",) # 指定需要的字段
class StaffModelSerializer(serializers.ModelSerializer):
# 序列化输入
# queryset=Department.objects.all(), many=True(会报错 【】 列表赋值)去掉many
#此时序列化输出 department/duty时为对应的id
department = serializers.PrimaryKeyRelatedField(label="部门",
queryset=Department.objects.all(), )
duty = serializers.PrimaryKeyRelatedField(label="职责",
queryset=Duty.objects.all(), )
# read_only=True 只序列化输出 且外键是id值
# 获取外键对应的名字
department_name = serializers.SerializerMethodField()
duty_name = serializers.SerializerMethodField()
def get_department_name(self, obj):
print("xxxx", obj)
return obj.department.name
def get_duty_name(self, obj):
return obj.duty.name
class Meta:
model = Staff
fields = ("id", "name", "sex", "phone", "department_name", "duty_name", "department", "duty")
read_only_fields = ("id",)
write_only_fields = ("email",)
反序列化创建数据时
不能有many=True
drf生成接口文件
- 安装coreapi
pip install coreapi
- 配置drf
REST_FRAMEWORK = [
"DEFAULT_SCHEMA_CLASS": "rest_framework.schemas.AutoSchema",
]
- 配置主路由
from rest_framework.documentation import include_docs_urls
urlpatterns = [
...
path('docs/', include_docs_urls(title='站点页面标题'))
]
在地址栏访问http://xxxx:8000/docs/,即可以看到接口文档。