[DRF]入门-8 : drf自定义返回字段,并可以查看外键全部信息,及不影响get和post请求.

当我们使用drf时会遇到相关外键的问题, 当我们把外键的内容扩展开了之后post的时候就会报错,所以这个时候如何处理post信息和如何拿到我们想要的字段的内容就格外重要.
下方的示例就处理了上述问题

  1. 首先我们来定义数据模型
class user(AbstractUser):
    id = models.IntegerField(verbose_name="buc账号id", primary_key=True)
    username = models.CharField(verbose_name="员工工号", max_length=50, unique=True)
    
class PerformanceData(models.Model):
    device = models.TextField(verbose_name="设备")
    deviceprop = models.TextField(verbose_name="设备信息")
    createdate = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    cpulist = models.TextField(verbose_name="CPU数据列表")
    psslist = models.TextField(verbose_name="PSS数据列表")
    gpulist = models.TextField(verbose_name="GPU数据列表")
    imagelist = models.TextField(verbose_name="图片列表")
    processname = models.TextField(verbose_name="图片列表")
    user = models.ForeignKey("user", on_delete=models.CASCADE)
  1. 定义完模型之后就要对模型进行序列化了
class UserSerializers(serializers.ModelSerializer):
    class Meta:
        model = user
        fields = "__all__"

class PerformanceDataSerializers(serializers.ModelSerializer):
    createdate = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    user = UserSerializers(read_only=True)
    
    class Meta:
        model = PerformanceData
        fields = "__all__"

    def __init__(self, instance=None, data=..., **kwargs):
        if data is Ellipsis:
            fields = kwargs.pop("fields", None)
            super().__init__(instance, **kwargs)
            if fields is not None:
                allow = set(fields)  # 本次的字段集
                existing = set(self.fields)  # 全部字段集
                for f in existing - allow:  # 去除字段集
                    self.fields.pop(f)
        else:
            super().__init__(instance, data=data, **kwargs)
  1. 序列化完毕之后就要处理view类了
class PerformanceDataViewSets(viewsets.ModelViewSet):
    queryset = PerformanceData.objects.all()
    serializer_class = PerformanceDataSerializers
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    ordering_fields = ["id"]
    filterset_fields = ["user"]

    # 主要用于分别我具体要拿到那些字段
    def get_serializer(self, *args, **kwargs):
        fields = self.request.query_params.get("fields", None)
        if fields:
            kwargs["fields"] = fields.split(",")
        return super().get_serializer(*args, **kwargs)

	# 主要是在post的时候对user进行处理
    def perform_create(self, serializer):
        user_id = self.request.data.get("user")
        user_item = user.objects.get(id=user_id)
        serializer.save(user=user_item)
        return super().perform_create(serializer)

你可能感兴趣的:(python,python,开发语言,restful,http,后端)