drf中常用的欄位及用法

认真的六六發表於2024-04-13

【序列化常見欄位】

其實就是巢狀,字典中物件巢狀字典,就用DictField,物件套列表用ListField

【序列化常見欄位引數】

validators	:該欄位使用的驗證器--》欄位自己的校驗[1 max_lenght 2 validators ],區域性鉤子,全域性鉤子 
	name=serializer.CharField(validators=[valida_name])

PS:翻譯函式

# 翻譯函式---》做好國際化
from django.utils.translation import gettext_lazy as _
def index(request):
    res=_('Not a valid string')
    print(res)
    return HttpResponse(res)

【多表關聯序列化和反序列化】

(source欄位)
  1.可以跨表查詢
  2.可以定製返回欄位名,必須跟欄位對應
  3.所有欄位都可以被轉成CharField

 1 models.py
 2 
 3 
 4 from django.db import models
 5 
 6 
 7 # Create your models here.
 8 
 9 class Book(models.Model):
10     name = models.CharField(max_length=50)
11     price = models.DecimalField(max_digits=5, decimal_places=2)
12     pub_date = models.DateField()
13     publish = models.ForeignKey('Publish', on_delete=models.CASCADE, null=True)
14     author = models.ManyToManyField('Author')
15 
16     def __str__(self):
17         return self.name

23 class Publish(models.Model):
24     name = models.CharField(max_length=30)
25     email = models.EmailField()
26     city = models.CharField(max_length=30)
27 
28     def __str__(self):
29         return self.name
30 
31 
32 class Author(models.Model):
33     name = models.CharField(max_length=30)
34     age = models.IntegerField()
35 
36     def __str__(self):
37         return self.name

(定製返回欄位)

ListField  DictField

  # 需求:後期想實現如下格式返回的資料

{name:書名,price:價格,publish:{name:出版社名,addr:地址},authors:[{},{}]}

方式一:

  在表模型中定義方法,在序列化器中做對映

  

第二種方法:在模型類中寫方法

  透過SerializerMethodField,配合get_欄位名使用

第三種

透過子序列化器定製返回欄位

ser.py

# =========================透過子序列化器定製返回欄位
# 把book表中的publish欄位也返回,
class PublishSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField()
    email = serializers.EmailField()
    city = serializers.CharField()


class AuthorSerializer(serializers.Serializer):
    name = serializers.CharField()
    age = serializers.IntegerField()


class BookSerializer(serializers.Serializer):
    name = serializers.CharField()
    price = serializers.DecimalField(max_digits=5, decimal_places=2)
    pub_date = serializers.DateField()
    # 子序列化器,也可以改欄位
    publish_detail = PublishSerializer(source='publish')
    # 序列化多條
    author = AuthorSerializer(many=True)

反序列化儲存

形式:

{name:書名,price:11,publish:2,authors:[1,2]}

新增反序列化儲存

修改反序列化儲存

【ModelSerializer使用】



相關文章