Django一分钟:DRF模型序列化器处理关联关系的示例与注意事项

news/2024/10/4 1:04:16 标签: django, 数据库, web, python
webkit-tap-highlight-color: rgba(0, 0, 0, 0);">

DRF的ModelSerializer序列化器与Django的Model模型紧密映射,本文将通过简单的示例介绍几种处理关联关系的方法。

1. 创建模型和初始数据

创建模型

python">from django.db import models

class Product(models.Model):
    product_name = models.CharField(max_length=255)
    quantity = models.IntegerField()

class Component(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='components')
    component_name = models.CharField(max_length=255)
    code = models.CharField(max_length=255)
    quantity = models.IntegerField()

    class Meta:
        ordering = ['product']

    def __str__(self):
        return f'{self.code}-{self.component_name}'

创建数据

python">>>> from api.models import Product, Component
>>> p1 = Product.objects.create(product_name="盖子", quantity=30)
>>> Component.objects.create(product=p1, component_name='纤维板', code='XYB', quantity=5)
>>> Component.objects.create(product=p1, component_name='螺丝', code='LS', quantity=10)
>>> Component.objects.create(product=p1, component_name='密封条', code='MFT', quantity=20)

2. 字符串关系字段

使用StringRelatedField

python">from rest_framework import serializers
from .models import Product

class ProductSerializer(serializers.ModelSerializer):
    components = serializers.StringRelatedField(many=True)

    class Meta:
        model = Product
        fields = ['product_name', 'quantity', 'components']

执行查询和序列化

python">>>> from api.models import Product
>>> p1 = Product.objects.prefetch_related('components').get(pk=1)
>>> from api.serializers import ProductSerializer
>>> ps = ProductSerializer(p1)
>>> ps.data
# {'product_name': '盖子', 'quantity': 30, 'components': ['XYB-纤维板', 'LS-螺丝', 'MFT-密封条']}

效果如下:

python">{
    'product_name': '盖子', 
    'quantity': 30, 
    'components': [
        'XYB-纤维板', 
        'LS-螺丝', 
        'MFT-密封条'
    ]
}

注意观察获取查询集的代码:Product.objects.prefetch_related('components').get(pk=1)不难发现我们使用了prefetch_related来获取查询集,如果一次查询大量的Product,不使用prefetch_related将会导致严重的性能问题(N+1问题)。DRF的序列化器不会为你自动优化。当然我们的示例中影响不大,因为只获取了一个查询集。

3. 主键关系字段

使用PrimaryKeyRelatedField

python">from rest_framework import serializers
from .models import Product

class ProductSerializer(serializers.ModelSerializer):
    components =  serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = Product
        fields = ['product_name', 'quantity', 'components']

效果如下:

python">{
    'product_name': '盖子', 
    'quantity': 30, 
    'components': [
        1, 
        2, 
        3
    ]
}

4. 指定关系字段

使用SlugRelatedField可以指定字段来表示关联关系:

python">from rest_framework import serializers
from .models import Product

class ProductSerializer(serializers.ModelSerializer):
    components =  serializers.SlugRelatedField(
        many=True,
        read_only=True,
        slug_field='code'
     )

    class Meta:
        model = Product
        fields = ['product_name', 'quantity', 'components']

效果如下:

python">{
    'product_name': '盖子', 
    'quantity': 30, 
    'components': [
        'XYB', 
        'LS', 
        'MFT'
    ]
}

5. 嵌套序列化器

python">from rest_framework import serializers
from .models import Product, Component

class ComponentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Component
        fields = ['component_name', 'code', 'quantity']

class ProductSerializer(serializers.ModelSerializer):
    components =  ComponentSerializer(many=True, read_only=True)

    class Meta:
        model = Product
        fields = ['product_name', 'quantity', 'components']

效果如下:

python">{
    "product_name": "盖子",
    "quantity": 30,
    "components": [
        {
            "component_name": "纤维板",
            "code": "XYB",
            "quantity": 5
        },
        {
            "component_name": "螺丝",
            "code": "LS",
            "quantity": 10
        },
        {
            "component_name": "密封条",
            "code": "MFT",
            "quantity": 20
        }
    ]
}

6. 可写嵌套

默认上面创建的嵌套序列化器是只读的,可写嵌套需要实现updatecreate两者或其一:

python">from rest_framework import serializers
from .models import Product, Component

class ComponentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Component
        fields = ['component_name', 'code', 'quantity']

class ProductSerializer(serializers.ModelSerializer):
    components =  ComponentSerializer(many=True)

    class Meta:
        model = Product
        fields = ['product_name', 'quantity', 'components']

    def create(self, validated_data):
        components_data = validated_data.pop('components')
        product = Product.objects.create(**validated_data)
        for component_data in components_data:
            Component.objects.create(product=product, **component_data)
        return product

可以使用此序列化器创建实例:

python">>>> data = {
    "product_name": "电机",
    "quantity": 1,
    "components": [
        {
            "component_name": "铝型材",
            "code": "LXC",
            "quantity": 5
        },
        {
            "component_name": "螺栓",
            "code": "LSHUN",
            "quantity": 10
        },
    ]
}
>>> from api.serializers import ProductSerializer
>>> s = ProductSerializer(data=data)
>>> s.is_valid()
# True
>>> s.save()
# <Product: Product object (2)>

7. 总结注意事项

  1. 关联关系注意使用prefetch_related获取查询集。
  2. 可写嵌套序列化器必须自己实现create方法update方法两者或其一。

http://www.niftyadmin.cn/n/5689223.html

相关文章

【Orange Pi 5 嵌入应用编程】-用户空间I2C通信

用户空间I2C通信 文章目录 用户空间I2C通信1、理解I2C协议1.1 什么是I2C协议1.2 I2C协议如何工作1.3 I2C数据传输步骤1.4 单主机多从机1.5 多主机多从机1.6 I2C的优缺点2、嵌入式Linux系统中的I2C3、Orange Pi 5的I2C配置及编程3.1 I2C配置3.2 I2C通信实现3.2.1 I2C通信函数定义…

Python知识点:如何使用Edge Impulse与Python进行机器学习模型部署

开篇&#xff0c;先说一个好消息&#xff0c;截止到2025年1月1日前&#xff0c;翻到文末找到我&#xff0c;赠送定制版的开题报告和任务书&#xff0c;先到先得&#xff01;过期不候&#xff01; 使用Edge Impulse与Python进行机器学习模型部署 在物联网和边缘计算领域&#x…

【前沿 热点 顶会】NIPS 2024中分割有关的论文

XMask3D&#xff1a;开放词汇 3D 语义分割的跨模式 Masking 推理 开放词汇 3D 语义切分的现有方法主要集中在建立包含 3D、 2D 和文本形态的统一特征空间。然而&#xff0c;传统的技术&#xff0c;如全局特征对齐或视觉语言模型蒸馏&#xff0c;往往只强制实施近似对应&#x…

演示:基于WPF的DrawingVisual开发的频谱图和律动图

一、目的&#xff1a;基于WPF的DrawingVisual开发的频谱图和律动图 二、效果演示 波形图 极坐标 律动图极坐标图 律动图柱状图 Dock布局组合效果 三、环境 VS2022,Net7,Win10&#xff0c;NVIDIA RTX A2000 四、主要功能 支持设置起始频率&#xff0c;终止频率&#xff0c;中心…

Java 之深入理解 String、StringBuilder、StringBuffer

前言 由于发现 String、StringBuilder、StringBuffer 面试的时候会经常问到&#xff0c;这里就顺便总结一下&#xff1a;本文重点会以这三个字符串类的性能、线程安全、存储结构这三个方面进行分析 ✨上期回顾&#xff1a;Java 哈希表 ✨目录 前言 String 介绍 String 的不可变…

浅析Golang的Context

文章目录 1. 简介2. 常见用法2.1 控制goroutine的生命周期&#xff08;cancel&#xff09;2.2 传递超时&#xff08;Timeout&#xff09;信息2.3 传递截止时间&#xff08;Deadline&#xff09;2.4 传递请求范围内的全局数据 &#xff08;value&#xff09; 3 特点3.1 上下文的…

解决pycharm中matplotlab画图不能显示中文的错误

大家在用matplotlab画图时想要设置的中文字体通常显示不出来&#xff0c;这是因为Matplotlib在渲染图形时找不到某些特定的字形&#xff08;Glyph&#xff09;&#xff0c;尤其是中文字符。这些字符在你的默认字体中不存在&#xff0c;因此Matplotlib无法正确显示它们。 可以通…

zookeeper 服务搭建(单机)

安装步骤 从码云下载 git clone apache-zookeeper-3.5.9-bin: apache-zookeeper-3.5.9-bin重命名 mv apache-zookeeper-3.5.9-bin/ apache-zookeeper-3.5.9添加执行权限 进入bin目录 cd bin/添加可执行权限 chmod ux *.sh在安装目录下创建data目录 mkdir data 修改配置文件 修…