简体   繁体   English

用于自定义表单数据的Django REST框架序列化程序

[英]Django REST framework serializer for custom form data

I've started learning how to use the Django REST Framework along with React and I have a quick question. 我已经开始学习如何使用Django REST框架和React,我有一个简单的问题。 I made a form and use CreateAPIView and UpdateAPIView to create/update items, respectively. 我制作了一个表单并使用CreateAPIViewUpdateAPIView分别创建/更新项目。 But how do I get the contents to populate my <select> field if the list comes from a variable in one of my models? 但是如果列表来自我的某个模型中的变量,如何让内容填充我的<select>字段?

from model_utils import Choices

class Author(models.Model):
    GENDER = Choices('male', 'female', "I don't know really")  # How do I get this?

    gender = models.CharField(max_length=10, choices=GENDER)

What will the serializer and views for Author.GENDER look like since it's not a model? Author.GENDER序列化程序视图会是什么样子,因为它不是模型?

At the moment, this is what I have for now. 目前,这就是我现在所拥有的。

Django (nothing out of the ordinary here, I think.). Django(我认为这里没什么特别的。)

# Serializer.
class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ('id', 'gender')

# View
class AuthorUpdateView(UpdateAPIView):
    queryset = Author.objects.filter(deleted_at__isnull=True)
    serializer_class = AuthorSerializer

React. 反应。

componentDidMount() {
  const pk = this.props.match.params.pk
  axios.get(`http://localhost:8000/api/authors/${pk}`)
    .then(response => {
      const pk = response.data.id
      const gender = response.data.gender
      this.setState({gender})
    })
    .catch(err => console.log(err))
}

I'm open to any direction or concept you might have when using DRF so I can also learn from how you would do it. 我对使用DRF时可能遇到的任何方向或概念持开放态度,因此我也可以学习如何做到这一点。

Use viewset to combine the logic for a set of your related views (list, create, update) 使用viewset组合一组相关视图的逻辑(列表,创建,更新)

class AuthorViewSet(ModelViewSet):
    queryset = Author.objects.filter(deleted_at__isnull=True)
    serializer_class = AuthorSerializer

Make a OPTIONS request to get the metadata for your resource, including the list of valid choices of gender field 发出OPTIONS请求以获取资源的元数据,包括gender字段的有效选择列表

Request 请求

OPTIONS /api/authors/

Response 响应

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "name": "Author List",
    "parses": [
        "application/json",
        "application/x-www-form-urlencoded",
        "multipart/form-data"
    ],
    "actions": {
        "POST": {
            "id": {
                "type": "integer",
                "required": false,
                "read_only": true,
                "label": "Id"
            },
            "gender": {
                "type": "choice",
                "required": true,
                "read_only": false,
                "label": "Gender",
                "choices": [
                    {
                        "value": "male",
                        "display_name": "male"
                    },
                    {
                        "value": "female",
                        "display_name": "female"
                    },
                    {
                        "value": "I don't know really",
                        "display_name": "I don't know really"
                    }
                ]
            }
        }
    }
}

As I mentioned in the comment, you could create a simple view to return the choices. 正如我在评论中提到的,您可以创建一个简单的视图来返回选择。

from rest_framework.decorators import api_view
from rest_framework.response import Response


@api_view()
def foo_view(request):
    choices = [i[0] for i in Author.GENDER]
    return Response(choices)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM