gpt4 book ai didi

python - Django REST Framework - 教程 - 困惑

转载 作者:行者123 更新时间:2023-12-01 03:54:23 25 4
gpt4 key购买 nike

我将在 Tutorials 中讨论序列化器(serializers.Serializer不是 serializers.ModelSerializer)我对一件事感到困惑。

首先,我们将数据序列化为 Python 原生数据类型:

>>> snippet = Snippet(code="print('hello' + ' world'\n)")
>>> snippet.save()

>>> serializer = SnippetSerializer(snippet)
>>> serializer.data
{'style': 'friendly', 'code': "print('hello' + ' world'\n)", 'language': 'python', 'title': '', 'pk': 2, 'linenos': False}

这里的问题是,我们没有发送语言或样式字段中的任何选择字段选项。

如果我们看一下serializer对象,那么它包括我们拥有的所有选择:

>>> serializer
SnippetSerializer(<Snippet: Snippet object>):
pk = IntegerField(read_only=True)
title = CharField(allow_blank=True, max_length=100, required=False)
code = CharField(style={'base_template': 'textarea.html'})
linenos = BooleanField(required=False)
language = ChoiceField(choices=[('abap', 'ABAP'), ('abnf', 'ABNF'), ('ada', 'Ada'), ('adl', 'ADL'), ('agda', 'Agda'), ('ahk', 'autohotkey'), ('alloy', 'Alloy'), ('antlr', 'ANTLR'), ('antlr-as', 'ANTLR With ActionScript Target'), ('antlr-cpp', 'ANTLR With CPP Target'), ('antlr-csharp', 'ANTLR With C# Target'), ('antlr-java', 'ANTLR With Java Target'), ('antlr-objc', 'ANTLR With ObjectiveC Target'), ('antlr-perl', 'ANTLR With Perl Target'), ('antlr-python', 'ANTLR With Python Target'), ('antlr-ruby', 'ANTLR With Ruby Target'), ('apacheconf', 'ApacheConf'), ('apl', 'APL'), ('applescript', 'AppleScript'), ('arduino', 'Arduino'), ('as', 'ActionScript'), ('as3', 'ActionScript 3'), ('aspectj', 'AspectJ'), ('aspx-cs', 'aspx-cs'), ('aspx-vb', 'aspx-vb'), ('asy', 'Asymptote'), ('at', 'AmbientTalk'), ('autoit', 'AutoIt'), ('awk', 'Awk'), ('basemake', 'Base Makefile'), ('bash', 'Bash'), ('bat', 'Batchfile'), ('bbcode', 'BBCode'),....

所以我的问题是,为什么我们不发送serializer对象。为什么只发送不包含选择选项的serializer.data。客户端如何知道必须选择哪些选项?

我也可能对客户端在本教程中的位置感到困惑。我还没有完全明白这对我来说是如何运作的。

最佳答案

选项方法

The OPTIONS method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. — RFC7231, Section 4.3.7.

如果你想让JS有meta information在该资源上,您可能需要实现一个 OPTIONS 方法,让 JS 处理返回的元数据,然后调整表单以创建新实例。

如果您遵循上面链接的 Django REST Framework 文档,您将能够自定义元数据中返回的内容以满足您的需求。

关于python - Django REST Framework - 教程 - 困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37751866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com