RelatedField to_representation phải được triển khai cho trường

Mục đích chính của bộ tuần tự hóa là chuyển đổi mô hình Django hay đúng hơn là bảng cơ sở dữ liệu thành định dạng có thể được chuyển qua internet, chẳng hạn như đầu ra JSON hoặc đầu ra XML

Điều này trở nên hơi phức tạp khi bạn có hai mô hình có liên quan với nhau thông qua khóa ngoại hoặc mối quan hệ nhiều-nhiều.  

Việc tuần tự hóa một mô hình có chứa khóa ngoại sang một mô hình khác có thể được thực hiện theo nhiều cách khác nhau tùy thuộc vào những gì bạn định làm với dữ liệu này. Phương pháp được sử dụng rộng rãi nhất là sử dụng bộ nối tiếp lồng nhau

Sử dụng bộ nối tiếp lồng nhau

Xem xét mối quan hệ giữa một bài hát và một nghệ sĩ. Có thể có nhiều bài hát, mỗi bài hát có thể thuộc về cùng một nghệ sĩ, do đó cần có khóa ngoại

Giả sử rằng chúng tôi muốn trình bày mô hình Nghệ sĩ theo cách nó bao gồm tất cả các bài hát được ghi bởi nghệ sĩ đó. Điều này có thể đạt được bằng cách sử dụng bộ nối tiếp lồng nhau

Khi sử dụng ArtistSerializer, phản hồi được trả về sẽ như thế này

Theo mặc định, bộ nối tiếp lồng nhau chỉ được đọc. Để sử dụng bộ nối tiếp này để xác thực đầu vào và ghi dữ liệu vào DB, người ta phải ghi đè rõ ràng các phương thức tạo [] hoặc cập nhật [] như được hiển thị bên dưới

Sử dụng quan hệ serializer mặc định

Việc viết các bộ nối tiếp lồng nhau thường có thể tránh được bằng cách sử dụng các loại quan hệ nối tiếp khác nhau được cung cấp bởi khung công tác Django REST mà bạn có thể tìm thấy.  

Trong hướng dẫn này, chúng tôi sẽ đề cập đến PrimaryKeyRelatedField và SlugRelatedField. Phần còn lại của các loại quan hệ bộ nối tiếp khá giống nhau và có thể được sử dụng thay thế cho nhau tùy thuộc vào trường hợp sử dụng của bạn

Trong mỗi loại này, bạn có thể tạo bộ nối tiếp chỉ đọc bằng cách đặt read_only=True hoặc bạn cũng có thể sử dụng những bộ này để ghi dữ liệu bằng cách xác thực đầu vào

Nếu bạn muốn làm cho chúng có thể ghi được, bạn chỉ cần đưa tham số bộ truy vấn vào bộ nối tiếp cùng với read_only=False  sẽ được sử dụng để xác thực đầu vào.  

Chúng ta hãy xem mối quan hệ serializer được sử dụng phổ biến nhất để giải thích thêm về điều này

Trường chính có liên quan

Nếu bạn đã có các đối tượng riêng lẻ của các trường liên quan, bạn chỉ có thể đánh số thứ tự khóa chính để xác định các đối tượng

Điều này sẽ được nối tiếp như sau

Để làm cho trình nối tiếp này có thể ghi được, hãy sử dụng các đối số sau

SlugLĩnh vực liên quan

Nếu mục tiêu của mối quan hệ cần được biểu diễn bằng một trường không phải là khóa chính, bạn có thể chỉ định trường bạn muốn sử dụng

Điều này sẽ được nối tiếp như sau

ghi chú kết thúc

Nếu bạn cần kiểm soát hoàn toàn cách các đối tượng và mối quan hệ được tạo/biểu diễn tại thời điểm tuần tự hóa dữ liệu hoặc nếu bạn cần hiển thị toàn bộ đối tượng tại thời điểm tuần tự hóa, sử dụng bộ tuần tự hóa lồng nhau là cách tiếp cận tốt hơn

Tuy nhiên, nếu bạn đang xây dựng một ứng dụng mà bạn đã có quyền truy cập vào các mô hình liên quan và bạn chỉ cần một mã định danh để tham chiếu chúng, thì tôi khuyên bạn nên sử dụng một trong các mối quan hệ bộ nối tiếp có sẵn

Các phương pháp xử lý quan hệ khóa ngoài ở trên trong bộ tuần tự hóa không chỉ dành cho các trường ForeignKey. Họ cũng áp dụng cho ManyToManyField và OneToOneField

Mở rộng tính hữu ích của bộ nối tiếp là điều mà chúng tôi muốn giải quyết. Tuy nhiên, đó không phải là một vấn đề tầm thường và sẽ cần một số công việc thiết kế nghiêm túc

— Russell Keith-Magee, nhóm người dùng Django

Bộ nối tiếp cho phép dữ liệu phức tạp như bộ truy vấn và phiên bản mô hình được chuyển đổi thành kiểu dữ liệu Python gốc, sau đó có thể dễ dàng kết xuất thành

from rest_framework.renderers import JSONRenderer

json = JSONRenderer[].render[serializer.data]
json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
7,
from rest_framework.renderers import JSONRenderer

json = JSONRenderer[].render[serializer.data]
json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
8 hoặc các kiểu nội dung khác. Bộ tuần tự hóa cũng cung cấp quá trình giải tuần tự hóa, cho phép dữ liệu đã phân tích cú pháp được chuyển đổi trở lại thành các loại phức tạp, sau lần đầu tiên xác thực dữ liệu đến

Các serializer của khung REST hoạt động rất giống với các lớp

from rest_framework.renderers import JSONRenderer

json = JSONRenderer[].render[serializer.data]
json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
9 và
description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
0 của Django. Nó cung cấp một lớp
description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
1 cung cấp cho bạn một cách tổng quát, mạnh mẽ để kiểm soát đầu ra của các câu trả lời của bạn, cũng như một lớp
description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
2 cung cấp một lối tắt hữu ích để tạo các bộ tuần tự hóa xử lý các phiên bản mô hình và bộ truy vấn

Khai báo serializers

Hãy bắt đầu bằng cách tạo một đối tượng đơn giản mà chúng ta có thể sử dụng cho các mục đích ví dụ

class Comment[object]:
    def __init__[self, email, content, created=None]:
        self.email = email
        self.content = content
        self.created = created or datetime.datetime.now[]

comment = Comment[email='leila@example.com', content='foo bar']

Chúng ta sẽ khai báo một bộ tuần tự hóa mà chúng ta có thể sử dụng để tuần tự hóa và giải tuần tự hóa các đối tượng

description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
3

Khai báo một serializer trông rất giống với khai báo một biểu mẫu

________số 8_______

Phần đầu tiên của lớp serializer xác định các trường được tuần tự hóa/giải tuần tự hóa. Phương thức

description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
4 xác định cách các phiên bản chính thức được tạo khi giải tuần tự hóa dữ liệu

Phương thức

description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
4 là tùy chọn và chỉ được yêu cầu nếu chúng tôi muốn trình tuần tự hóa của mình hỗ trợ giải tuần tự hóa thành các thể hiện đối tượng chính thức. Nếu chúng ta không xác định phương thức này, thì dữ liệu giải tuần tự hóa sẽ chỉ trả về một từ điển các mục

Nối tiếp các đối tượng

Bây giờ chúng ta có thể sử dụng

description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
6 để tuần tự hóa một nhận xét hoặc danh sách các nhận xét. Một lần nữa, sử dụng lớp
description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
1 giống như sử dụng lớp
from rest_framework.renderers import JSONRenderer

json = JSONRenderer[].render[serializer.data]
json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
9

serializer = CommentSerializer[comment]
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime[2012, 8, 22, 16, 20, 9, 822774]}

Tại thời điểm này, chúng tôi đã dịch phiên bản mô hình thành các kiểu dữ liệu gốc của Python. Để hoàn tất quy trình lập số sê-ri, chúng tôi kết xuất dữ liệu thành

description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
9

from rest_framework.renderers import JSONRenderer

json = JSONRenderer[].render[serializer.data]
json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'

Tùy chỉnh biểu diễn trường

Đôi khi khi sắp xếp theo thứ tự các đối tượng, bạn có thể không muốn biểu diễn mọi thứ chính xác như trong mô hình của mình

Nếu bạn cần tùy chỉnh giá trị được tuần tự hóa của một trường cụ thể, bạn có thể thực hiện việc này bằng cách tạo phương thức

from StringIO import StringIO
from rest_framework.parsers import JSONParser

stream = StringIO[json]
data = JSONParser[].parse[stream]
0. Ví dụ: nếu bạn cần hiển thị một số đánh dấu từ trường văn bản

description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]

Các phương pháp này về cơ bản là đảo ngược của

from StringIO import StringIO
from rest_framework.parsers import JSONParser

stream = StringIO[json]
data = JSONParser[].parse[stream]
1 [xem Xác thực bên dưới. ]

khử lưu huỳnh đối tượng

Deserialization là tương tự. Trước tiên, chúng tôi phân tích một luồng thành các kiểu dữ liệu gốc của Python

from StringIO import StringIO
from rest_framework.parsers import JSONParser

stream = StringIO[json]
data = JSONParser[].parse[stream]

sau đó chúng tôi khôi phục các kiểu dữ liệu gốc đó thành một thể hiện đối tượng được điền đầy đủ

serializer = CommentSerializer[data=data]
serializer.is_valid[]
# True
serializer.object
# 

Khi giải tuần tự hóa dữ liệu, chúng ta có thể tạo một phiên bản mới hoặc cập nhật một phiên bản hiện có

serializer = CommentSerializer[data=data]           # Create new instance
serializer = CommentSerializer[comment, data=data]  # Update `comment`

Theo mặc định, các bộ nối tiếp phải được truyền giá trị cho tất cả các trường bắt buộc, nếu không chúng sẽ gây ra lỗi xác thực. Bạn có thể sử dụng đối số

from StringIO import StringIO
from rest_framework.parsers import JSONParser

stream = StringIO[json]
data = JSONParser[].parse[stream]
2 để cho phép cập nhật từng phần

serializer = CommentSerializer[comment, data={'content': u'foo bar'}, partial=True]  # Update `comment` with partial data

Thẩm định

Khi giải tuần tự hóa dữ liệu, bạn luôn cần gọi ____17_______3 trước khi thử truy cập đối tượng đã giải tuần tự hóa. Nếu xảy ra bất kỳ lỗi xác thực nào, thuộc tính

from StringIO import StringIO
from rest_framework.parsers import JSONParser

stream = StringIO[json]
data = JSONParser[].parse[stream]
4 sẽ chứa một từ điển đại diện cho các thông báo lỗi kết quả. Ví dụ

serializer = CommentSerializer[data={'email': 'foobar', 'content': 'baz'}]
serializer.is_valid[]
# False
serializer.errors
# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}

Mỗi khóa trong từ điển sẽ là tên trường và các giá trị sẽ là danh sách các chuỗi của bất kỳ thông báo lỗi nào tương ứng với trường đó. Khóa

from StringIO import StringIO
from rest_framework.parsers import JSONParser

stream = StringIO[json]
data = JSONParser[].parse[stream]
5 cũng có thể xuất hiện và sẽ liệt kê bất kỳ lỗi xác thực chung nào

Khi giải tuần tự hóa danh sách các mục, lỗi sẽ được trả về dưới dạng danh sách từ điển đại diện cho từng mục đã giải tuần tự hóa

Xác thực cấp trường

Bạn có thể chỉ định xác thực cấp trường tùy chỉnh bằng cách thêm các phương thức

from StringIO import StringIO
from rest_framework.parsers import JSONParser

stream = StringIO[json]
data = JSONParser[].parse[stream]
6 vào lớp con
description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
1 của bạn. Chúng tương tự như các phương thức
from StringIO import StringIO
from rest_framework.parsers import JSONParser

stream = StringIO[json]
data = JSONParser[].parse[stream]
8 trên các biểu mẫu Django, nhưng chấp nhận các đối số hơi khác

Họ lấy một từ điển gồm các thuộc tính được giải tuần tự hóa làm đối số đầu tiên và tên trường trong từ điển đó làm đối số thứ hai [sẽ là tên của trường hoặc giá trị của đối số

from StringIO import StringIO
from rest_framework.parsers import JSONParser

stream = StringIO[json]
data = JSONParser[].parse[stream]
9 cho trường, nếu một trường được cung cấp]

Các phương pháp

from StringIO import StringIO
from rest_framework.parsers import JSONParser

stream = StringIO[json]
data = JSONParser[].parse[stream]
1 của bạn chỉ nên trả về từ điển
serializer = CommentSerializer[data=data]
serializer.is_valid[]
# True
serializer.object
# 
1 hoặc tăng một số
serializer = CommentSerializer[data=data]
serializer.is_valid[]
# True
serializer.object
# 
2. Ví dụ

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
0

Xác thực cấp đối tượng

Để thực hiện bất kỳ xác thực nào khác yêu cầu quyền truy cập vào nhiều trường, hãy thêm một phương thức có tên là

serializer = CommentSerializer[data=data]
serializer.is_valid[]
# True
serializer.object
# 
3 vào lớp con
description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
1 của bạn. Phương thức này nhận một đối số duy nhất, đó là từ điển
serializer = CommentSerializer[data=data]
serializer.is_valid[]
# True
serializer.object
# 
1. Nó sẽ tăng một
serializer = CommentSerializer[data=data]
serializer.is_valid[]
# True
serializer.object
# 
2 nếu cần, hoặc chỉ cần trả về
serializer = CommentSerializer[data=data]
serializer.is_valid[]
# True
serializer.object
# 
1. Ví dụ

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
1

Lưu trạng thái đối tượng

Để lưu các đối tượng được giải tuần tự hóa được tạo bởi bộ tuần tự hóa, hãy gọi phương thức

serializer = CommentSerializer[data=data]
serializer.is_valid[]
# True
serializer.object
# 
8

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
2

Hành vi mặc định của phương thức là chỉ cần gọi

serializer = CommentSerializer[data=data]
serializer.is_valid[]
# True
serializer.object
# 
8 trên thể hiện của đối tượng đã giải tuần tự hóa. Bạn có thể ghi đè hành vi lưu mặc định bằng cách ghi đè phương thức
serializer = CommentSerializer[data=data]           # Create new instance
serializer = CommentSerializer[comment, data=data]  # Update `comment`
0 trên lớp serializer

Các dạng xem chung được cung cấp bởi khung REST gọi phương thức

serializer = CommentSerializer[data=data]
serializer.is_valid[]
# True
serializer.object
# 
8 khi cập nhật hoặc tạo các thực thể

Xử lý các đối tượng lồng nhau

Các ví dụ trước rất phù hợp để xử lý các đối tượng chỉ có kiểu dữ liệu đơn giản, nhưng đôi khi chúng ta cũng cần có khả năng biểu diễn các đối tượng phức tạp hơn, trong đó một số thuộc tính của đối tượng có thể không phải là kiểu dữ liệu đơn giản như chuỗi, ngày tháng hoặc số nguyên

Bản thân lớp

description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
1 là một loại của
serializer = CommentSerializer[data=data]           # Create new instance
serializer = CommentSerializer[comment, data=data]  # Update `comment`
3 và có thể được sử dụng để biểu diễn các mối quan hệ trong đó một loại đối tượng được lồng vào bên trong một loại đối tượng khác

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
3

Nếu một đại diện lồng nhau có thể tùy ý chấp nhận giá trị

serializer = CommentSerializer[data=data]           # Create new instance
serializer = CommentSerializer[comment, data=data]  # Update `comment`
4, bạn nên chuyển cờ
serializer = CommentSerializer[data=data]           # Create new instance
serializer = CommentSerializer[comment, data=data]  # Update `comment`
5 cho bộ nối tiếp lồng nhau

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
4

Tương tự, nếu một đại diện lồng nhau phải là một danh sách các mục, bạn nên chuyển cờ

serializer = CommentSerializer[data=data]           # Create new instance
serializer = CommentSerializer[comment, data=data]  # Update `comment`
6 cho chuỗi được sắp xếp lồng nhau

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
5

Việc xác thực các đối tượng lồng nhau sẽ hoạt động giống như trước đây. Lỗi với các đối tượng lồng nhau sẽ được lồng dưới tên trường của đối tượng lồng nhau

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
6

Xử lý nhiều đối tượng

Lớp

description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
1 cũng có thể xử lý tuần tự hóa hoặc giải tuần tự hóa danh sách các đối tượng

Tuần tự hóa nhiều đối tượng

Để tuần tự hóa một bộ truy vấn hoặc danh sách các đối tượng thay vì một thể hiện đối tượng đơn lẻ, bạn nên chuyển cờ

serializer = CommentSerializer[data=data]           # Create new instance
serializer = CommentSerializer[comment, data=data]  # Update `comment`
6 khi khởi tạo bộ tuần tự hóa. Sau đó, bạn có thể chuyển một bộ truy vấn hoặc danh sách các đối tượng được sắp xếp theo thứ tự

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
7

Deserializing nhiều đối tượng để tạo

Để giải tuần tự hóa danh sách dữ liệu đối tượng và tạo nhiều thể hiện đối tượng trong một lần truyền, bạn cũng nên đặt cờ

serializer = CommentSerializer[data=data]           # Create new instance
serializer = CommentSerializer[comment, data=data]  # Update `comment`
6 và chuyển danh sách dữ liệu cần giải tuần tự hóa

Điều này cho phép bạn viết các dạng xem tạo nhiều mục khi yêu cầu

serializer = CommentSerializer[comment, data={'content': u'foo bar'}, partial=True]  # Update `comment` with partial data
0 được thực hiện

Ví dụ

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
8

Bạn cũng có thể giải tuần tự hóa danh sách các đối tượng như một phần của bản cập nhật hàng loạt cho nhiều mục hiện có. Trong trường hợp này, bạn cần cung cấp cả danh sách hoặc bộ truy vấn các mục hiện có, cũng như danh sách dữ liệu để cập nhật các mục đó với

Điều này cho phép bạn viết các dạng xem cập nhật hoặc tạo nhiều mục khi có yêu cầu

serializer = CommentSerializer[comment, data={'content': u'foo bar'}, partial=True]  # Update `comment` with partial data
1

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
9

Theo mặc định, các bản cập nhật hàng loạt sẽ bị giới hạn trong việc cập nhật các phiên bản đã tồn tại trong bộ truy vấn được cung cấp

Khi thực hiện cập nhật hàng loạt, bạn có thể muốn cho phép tạo các mục mới và xóa các mục bị thiếu. Để làm như vậy, hãy chuyển

serializer = CommentSerializer[comment, data={'content': u'foo bar'}, partial=True]  # Update `comment` with partial data
2 cho bộ nối tiếp

serializer = CommentSerializer[comment]
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime[2012, 8, 22, 16, 20, 9, 822774]}
0

Việc chuyển

serializer = CommentSerializer[comment, data={'content': u'foo bar'}, partial=True]  # Update `comment` with partial data
2 đảm bảo rằng mọi hoạt động cập nhật sẽ ghi đè hoàn toàn bộ truy vấn hiện có, thay vì chỉ cập nhật các đối tượng hiện có

Thực hiện cập nhật hàng loạt phức tạp hơn một chút so với thực hiện tạo hàng loạt, bởi vì bộ tuần tự hóa cần một cách để xác định cách khớp các mục trong dữ liệu đến với các phiên bản đối tượng hiện có

Theo mặc định, lớp serializer sẽ sử dụng khóa

serializer = CommentSerializer[comment, data={'content': u'foo bar'}, partial=True]  # Update `comment` with partial data
4 trên dữ liệu đến để xác định danh tính chính tắc của một đối tượng. Nếu bạn cần thay đổi hành vi này, bạn nên ghi đè phương thức
serializer = CommentSerializer[comment, data={'content': u'foo bar'}, partial=True]  # Update `comment` with partial data
5 trên lớp
description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
1. Ví dụ

serializer = CommentSerializer[comment]
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime[2012, 8, 22, 16, 20, 9, 822774]}
1

Để ánh xạ các mục dữ liệu đến với các thể hiện đối tượng tương ứng của chúng, phương thức

serializer = CommentSerializer[comment, data={'content': u'foo bar'}, partial=True]  # Update `comment` with partial data
7 sẽ được gọi cả đối với dữ liệu đến và đối với biểu diễn được tuần tự hóa của các đối tượng hiện có

Có một số trường hợp bạn cần cung cấp ngữ cảnh bổ sung cho bộ tuần tự hóa ngoài đối tượng được tuần tự hóa. Một trường hợp phổ biến là nếu bạn đang sử dụng bộ tuần tự hóa bao gồm các mối quan hệ siêu liên kết, yêu cầu bộ tuần tự hóa phải có quyền truy cập vào yêu cầu hiện tại để nó có thể tạo các URL đủ điều kiện đúng cách

Bạn có thể cung cấp ngữ cảnh bổ sung tùy ý bằng cách chuyển đối số

serializer = CommentSerializer[comment, data={'content': u'foo bar'}, partial=True]  # Update `comment` with partial data
8 khi khởi tạo trình nối tiếp. Ví dụ

serializer = CommentSerializer[comment]
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime[2012, 8, 22, 16, 20, 9, 822774]}
2

Từ điển ngữ cảnh có thể được sử dụng trong bất kỳ logic trường bộ tuần tự hóa nào, chẳng hạn như phương pháp

serializer = CommentSerializer[comment, data={'content': u'foo bar'}, partial=True]  # Update `comment` with partial data
9 tùy chỉnh, bằng cách truy cập thuộc tính
serializer = CommentSerializer[data={'email': 'foobar', 'content': 'baz'}]
serializer.is_valid[]
# False
serializer.errors
# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}
0

-

Thường thì bạn sẽ muốn các lớp serializer ánh xạ chặt chẽ với các định nghĩa mô hình. Lớp

description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
2 cho phép bạn tự động tạo một lớp Trình nối tiếp với các trường tương ứng với các trường Mô hình

serializer = CommentSerializer[comment]
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime[2012, 8, 22, 16, 20, 9, 822774]}
3

Theo mặc định, tất cả các trường mô hình trên lớp sẽ được ánh xạ tới các trường bộ nối tiếp tương ứng

Bất kỳ mối quan hệ nào chẳng hạn như khóa ngoại trên mô hình sẽ được ánh xạ tới

serializer = CommentSerializer[data={'email': 'foobar', 'content': 'baz'}]
serializer.is_valid[]
# False
serializer.errors
# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}
2. Các trường mô hình khác sẽ được ánh xạ tới trường bộ nối tiếp tương ứng

Ghi chú. Khi xác thực được áp dụng cho

description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
2, cả trường bộ lập số sê-ri và trường mô hình tương ứng của chúng phải xác thực chính xác. Nếu bạn có các trường tùy chọn trên mô hình của mình, hãy đảm bảo đặt chính xác
serializer = CommentSerializer[data={'email': 'foobar', 'content': 'baz'}]
serializer.is_valid[]
# False
serializer.errors
# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}
4 trên trường mô hình, cũng như đặt
serializer = CommentSerializer[data=data]           # Create new instance
serializer = CommentSerializer[comment, data=data]  # Update `comment`
5 trên trường bộ nối tiếp

Chỉ định các trường nào sẽ được bao gồm

Nếu bạn chỉ muốn một tập hợp con của các trường mặc định được sử dụng trong bộ nối tiếp mô hình, bạn có thể làm như vậy bằng cách sử dụng các tùy chọn

serializer = CommentSerializer[data={'email': 'foobar', 'content': 'baz'}]
serializer.is_valid[]
# False
serializer.errors
# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}
6 hoặc
serializer = CommentSerializer[data={'email': 'foobar', 'content': 'baz'}]
serializer.is_valid[]
# False
serializer.errors
# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}
7, giống như bạn làm với một
description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
0

Ví dụ

serializer = CommentSerializer[comment]
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime[2012, 8, 22, 16, 20, 9, 822774]}
4

Chỉ định tuần tự hóa lồng nhau

description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
2 mặc định sử dụng các khóa chính cho các mối quan hệ, nhưng bạn cũng có thể dễ dàng tạo các biểu diễn lồng nhau bằng cách sử dụng tùy chọn
from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
00

serializer = CommentSerializer[comment]
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime[2012, 8, 22, 16, 20, 9, 822774]}
5

Tùy chọn

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
00 phải được đặt thành một giá trị số nguyên cho biết độ sâu của các mối quan hệ sẽ được duyệt qua trước khi hoàn nguyên về biểu diễn phẳng

Nếu bạn muốn tùy chỉnh cách thực hiện tuần tự hóa [e. g. sử dụng

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
02], bạn sẽ cần tự xác định trường

Chỉ định trường nào sẽ ở chế độ chỉ đọc

Bạn có thể muốn chỉ định nhiều trường là chỉ đọc. Thay vì thêm từng trường một cách rõ ràng bằng thuộc tính

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
03, bạn có thể sử dụng tùy chọn Meta
from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
04, như vậy

serializer = CommentSerializer[comment]
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime[2012, 8, 22, 16, 20, 9, 822774]}
6

Các trường mô hình đã đặt

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
05 và các trường
from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
06 sẽ được đặt thành chỉ đọc theo mặc định và không cần thêm vào tùy chọn
from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
04

Chỉ định trường nào chỉ được ghi

Bạn có thể muốn chỉ định nhiều trường là chỉ ghi. Thay vì thêm từng trường một cách rõ ràng bằng thuộc tính

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
08, bạn có thể sử dụng tùy chọn Meta
from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
09, như vậy

serializer = CommentSerializer[comment]
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime[2012, 8, 22, 16, 20, 9, 822774]}
7

Chỉ định rõ ràng các trường

Bạn có thể thêm các trường bổ sung vào

description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
2 hoặc ghi đè lên các trường mặc định bằng cách khai báo các trường trên lớp, giống như cách bạn làm đối với lớp
description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
1

serializer = CommentSerializer[comment]
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime[2012, 8, 22, 16, 20, 9, 822774]}
8

Các trường bổ sung có thể tương ứng với bất kỳ thuộc tính nào hoặc có thể gọi được trên mô hình

trường quan hệ

Khi tuần tự hóa các phiên bản mô hình, có một số cách khác nhau mà bạn có thể chọn để thể hiện các mối quan hệ. Biểu diễn mặc định cho

description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
2 là sử dụng các khóa chính của các phiên bản liên quan

Các biểu diễn thay thế bao gồm sắp xếp theo thứ tự bằng cách sử dụng siêu kết nối, sắp xếp theo thứ tự các biểu diễn lồng nhau hoàn chỉnh hoặc sắp xếp theo thứ tự với một biểu diễn tùy chỉnh

Để biết đầy đủ chi tiết, hãy xem tài liệu về quan hệ bộ nối tiếp

Lớp

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
13 tương tự như lớp
description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
2 ngoại trừ việc nó sử dụng các siêu liên kết để biểu diễn các mối quan hệ, thay vì các khóa chính

Theo mặc định, bộ nối tiếp sẽ bao gồm trường

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
15 thay vì trường khóa chính

Trường url sẽ được biểu diễn bằng trường bộ đánh số thứ tự

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
16 và bất kỳ mối quan hệ nào trên mô hình sẽ được biểu diễn bằng cách sử dụng trường bộ đánh số thứ tự
from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
17

Bạn có thể bao gồm khóa chính một cách rõ ràng bằng cách thêm nó vào tùy chọn

serializer = CommentSerializer[data={'email': 'foobar', 'content': 'baz'}]
serializer.is_valid[]
# False
serializer.errors
# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}
6, chẳng hạn

serializer = CommentSerializer[comment]
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime[2012, 8, 22, 16, 20, 9, 822774]}
9

Các dạng xem siêu liên kết được xác định như thế nào

Cần phải có cách xác định chế độ xem nào sẽ được sử dụng để siêu liên kết đến các phiên bản mô hình

Theo mặc định, các siêu liên kết phải tương ứng với tên dạng xem phù hợp với kiểu

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
19 và tra cứu trường hợp bằng đối số từ khóa
from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
20

Bạn có thể thay đổi trường được sử dụng để tra cứu đối tượng bằng cách đặt tùy chọn

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
21. Giá trị của tùy chọn này phải tương ứng với cả kwarg trong URL conf và với một trường trên mô hình. Ví dụ

from rest_framework.renderers import JSONRenderer

json = JSONRenderer[].render[serializer.data]
json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
0

Lưu ý rằng

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
21 sẽ được sử dụng làm mặc định trên tất cả các trường siêu liên kết, bao gồm cả nhận dạng URL và bất kỳ mối quan hệ siêu liên kết nào

Đối với các yêu cầu cụ thể hơn, chẳng hạn như chỉ định tra cứu khác nhau cho từng trường, bạn sẽ muốn đặt rõ ràng các trường trên bộ tuần tự hóa. Ví dụ

from rest_framework.renderers import JSONRenderer

json = JSONRenderer[].render[serializer.data]
json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
1

Ghi đè hành vi trường URL

Tên của trường URL mặc định là 'url'. Bạn có thể ghi đè điều này trên toàn cầu, bằng cách sử dụng cài đặt

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
23

Bạn cũng có thể ghi đè điều này trên cơ sở từng bộ nối tiếp bằng cách sử dụng tùy chọn

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
24 trên bộ nối tiếp, như vậy

from rest_framework.renderers import JSONRenderer

json = JSONRenderer[].render[serializer.data]
json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
2

Ghi chú. Việc triển khai chế độ xem chung thường tạo tiêu đề

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
25 để đáp ứng các yêu cầu thành công của
serializer = CommentSerializer[comment, data={'content': u'foo bar'}, partial=True]  # Update `comment` with partial data
0. Bộ nối tiếp sử dụng tùy chọn
from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
24 sẽ không có tiêu đề này tự động được đưa vào chế độ xem. Nếu bạn cần làm như vậy, bạn cũng sẽ cần ghi đè phương thức
from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
28 của chế độ xem

Bạn cũng có thể ghi đè tên chế độ xem và trường tra cứu của trường URL mà không ghi đè trường một cách rõ ràng, bằng cách sử dụng các tùy chọn

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
29 và
from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
21, như vậy

from rest_framework.renderers import JSONRenderer

json = JSONRenderer[].render[serializer.data]
json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
3

Bạn có thể tạo các lớp con tùy chỉnh của

description = serializers.CharField[]
description_html = serializers.CharField[source='description', read_only=True]

def transform_description_html[self, obj, value]:
    from django.contrib.markup.templatetags.markup import markdown
    return markdown[value]
2 hoặc
from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
13 sử dụng một nhóm trường mặc định khác

Làm như vậy nên được coi là sử dụng nâng cao và sẽ chỉ cần thiết nếu bạn có một số yêu cầu về bộ nối tiếp cụ thể mà bạn thường cần lặp lại

Tự động sửa đổi các trường

Khi một bộ nối tiếp đã được khởi tạo, từ điển các trường được đặt trên bộ nối tiếp có thể được truy cập bằng thuộc tính

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
33. Truy cập và sửa đổi thuộc tính này cho phép bạn tự động sửa đổi bộ nối tiếp

Sửa đổi đối số

serializer = CommentSerializer[data={'email': 'foobar', 'content': 'baz'}]
serializer.is_valid[]
# False
serializer.errors
# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}
6 trực tiếp cho phép bạn thực hiện những điều thú vị như thay đổi đối số trên các trường bộ nối tiếp trong thời gian chạy, thay vì tại thời điểm khai báo bộ nối tiếp

Thí dụ

Ví dụ: nếu bạn muốn có thể đặt trường nào sẽ được sử dụng bởi trình tuần tự hóa tại thời điểm khởi tạo nó, bạn có thể tạo một lớp trình tuần tự hóa như vậy

from rest_framework.renderers import JSONRenderer

json = JSONRenderer[].render[serializer.data]
json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
4

Điều này sau đó sẽ cho phép bạn làm như sau

from rest_framework.renderers import JSONRenderer

json = JSONRenderer[].render[serializer.data]
json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
5

Tùy chỉnh các trường mặc định

Thuộc tính

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
35 là một từ điển ánh xạ các lớp mô hình thành các lớp nối tiếp. Ghi đè thuộc tính sẽ cho phép bạn đặt một tập hợp các lớp nối tiếp mặc định khác

Để tùy chỉnh nâng cao hơn thay vì chỉ thay đổi lớp bộ nối tiếp mặc định, bạn có thể ghi đè các phương thức

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
36 khác nhau. Làm như vậy sẽ cho phép bạn tùy chỉnh các đối số mà mỗi trường bộ nối tiếp được khởi tạo với. Mỗi phương thức trong số này có thể trả về một trường hoặc phiên bản bộ nối tiếp hoặc
serializer = CommentSerializer[data=data]           # Create new instance
serializer = CommentSerializer[comment, data=data]  # Update `comment`
4

get_pk_field

Chữ ký.

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
38

Trả về thể hiện của trường sẽ được sử dụng để biểu thị trường pk

get_nested_field

Chữ ký.

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
39

Trả về thể hiện trường sẽ được sử dụng để biểu thị một trường liên quan khi

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
00 được chỉ định là khác không

Lưu ý rằng đối số

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
41 sẽ là
serializer = CommentSerializer[data=data]           # Create new instance
serializer = CommentSerializer[comment, data=data]  # Update `comment`
4 đối với các mối quan hệ đảo ngược. Đối số
from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
43 sẽ là lớp mô hình cho mục tiêu của trường. Đối số
from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
44 sẽ là một boolean cho biết đây là mối quan hệ với một hay nhiều

Chữ ký.

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
45

Trả về thể hiện trường nên được sử dụng để biểu thị một trường liên quan khi không chỉ định _______8_______00 hoặc khi các biểu diễn lồng nhau đang được sử dụng và độ sâu bằng 0

Lưu ý rằng đối số

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
41 sẽ là
serializer = CommentSerializer[data=data]           # Create new instance
serializer = CommentSerializer[comment, data=data]  # Update `comment`
4 đối với các mối quan hệ đảo ngược. Đối số
from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
43 sẽ là lớp mô hình cho mục tiêu của trường. Đối số
from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
44 sẽ là một boolean cho biết đây là mối quan hệ với một hay nhiều

get_field

Chữ ký.

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
51

Trả về thể hiện trường nên được sử dụng cho các trường không quan hệ, không pk

Thí dụ

Bộ nối tiếp mô hình tùy chỉnh sau đây có thể được sử dụng làm lớp cơ sở cho bộ nối tiếp mô hình luôn loại trừ pk theo mặc định

from rest_framework.renderers import JSONRenderer

json = JSONRenderer[].render[serializer.data]
json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
6

Các gói bên thứ ba sau đây cũng có sẵn

Mongoengine ModelSerializer

Gói django-rest-framework-mongoengine cung cấp lớp serializer

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
52 hỗ trợ sử dụng MongoDB làm lớp lưu trữ cho khung Django REST

GeoFeatureModelSerializer

Gói django-rest-framework-gis cung cấp lớp serializer

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
53 hỗ trợ GeoJSON cho cả thao tác đọc và ghi

HStoreSerializer

Gói django-rest-framework-hstore cung cấp một

from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
54 để hỗ trợ trường mô hình django-hstore
from rest_framework import serializers

class CommentSerializer[serializers.Serializer]:
    email = serializers.EmailField[]
    content = serializers.CharField[max_length=200]
    created = serializers.DateTimeField[]

    def restore_object[self, attrs, instance=None]:
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get['email', instance.email]
            instance.content = attrs.get['content', instance.content]
            instance.created = attrs.get['created', instance.created]
            return instance
        return Comment[**attrs]
55 và tính năng ________8____56 của nó

To_representation Django là gì?

phương thức to_representation[bản thân, giá trị]. Phương thức này lấy mục tiêu của trường làm đối số giá trị và sẽ trả về biểu diễn sẽ được sử dụng để tuần tự hóa mục tiêu . Đối số giá trị thường sẽ là một thể hiện của mô hình.

Trường tra cứu trong khung nghỉ ngơi Django là gì?

Tra cứu là lớp chung để triển khai tra cứu . Tra cứu là một biểu thức truy vấn có vế trái, lhs ; .

Bộ nối tiếp trong khung phần còn lại của Django là gì?

Bộ nối tiếp trong Django REST Framework chịu trách nhiệm chuyển đổi đối tượng thành kiểu dữ liệu mà javascript và khung giao diện người dùng có thể hiểu được . Bộ tuần tự hóa cũng cung cấp quá trình giải tuần tự hóa, cho phép dữ liệu đã phân tích cú pháp được chuyển đổi trở lại thành các loại phức tạp, sau lần đầu tiên xác thực dữ liệu đến.

Chủ Đề