简体   繁体   English

如何在 Django Rest 框架中序列化 ChoiceFields?

[英]How to serialize ChoiceFields in Django Rest Framework?

First time Python user here, coming from Javascript world.第一次 Python 用户在这里,来自 Javascript 世界。 I'm able to retrieve my Model serialized to JSON from Django API and display it on the frontend written in React.我能够从 Django ZDB974238714CA4A4 中写入的 Django 检索序列化为 JSON 的 Model 并将其显示在前端 08A1 中。 But now I just added one more field priority to the Model that has multiple choices and I struggle to get these choices to the frontend (I want to display them in a dropdown and update REST API).但是现在我刚刚向具有多种选择的 Model 添加了一个字段priority ,我很难将这些选择带到前端(我想在下拉列表中显示它们并更新 REST API)。 Migration was successful and I can select choices from the back end but on the frontend I just get the default value set from migrations.迁移成功,我可以从后端选择 select 但在前端我只是从迁移中获取默认值。 Here is my code right now:这是我现在的代码:

models.py模型.py

class Todo(models.Model):
  title = models.CharField(max_length=120)
  description = models.TextField()
  completed = models.BooleanField(default=False)
  priority_choices = [
    ('High', 'High'),
    ('Medium', 'Medium'),
    ('Low', 'Low'),
  ]
  priority= models.CharField(max_length=6, choices=priority_choices, default='Low') #new field

  def __str__(self):
    return self.title

serializers.py序列化程序.py

from rest_framework import serializers
from .models import Todo

      
class TodoSerializer(serializers.ModelSerializer):
  class Meta:
    model = Todo
    fields = ('id', 'title', 'description', 'completed', 'priority')

views.py视图.py

class TodoView(viewsets.ModelViewSet):     
  serializer_class = TodoSerializer          
  queryset = Todo.objects.all()   

I just want the simplest solution, preferably to just update TodoSerializer(serializers.ModelSerializer) class inside serializers.py so that it would all come from this one Model.我只想要最简单的解决方案,最好只在 serializers.py 中更新TodoSerializer(serializers.ModelSerializer) class,这样它就都来自这个 Model。 Is that possible?那可能吗? Reading https://www.django-rest-framework.org/api-guide/fields/#choicefield is not clear for me whether I need to create a new class for the same Model just to retrieve ChoiceFields or if it's possible to do it all from one Class but whatever I try, I get syntax errors. Reading https://www.django-rest-framework.org/api-guide/fields/#choicefield is not clear for me whether I need to create a new class for the same Model just to retrieve ChoiceFields or if it's possible to do it all from one Class 但无论我尝试什么,都会出现语法错误。 Like I said, I'm very fresh to Python.就像我说的,我对 Python 很陌生。 Thanks.谢谢。

You can accomplish this using a SerializerMethodField您可以使用SerializerMethodField完成此操作

class TodoSerializer(serializers.ModelSerializer):
    priority_choices = serializers.SerializerMethodField()

    def get_priority_choices(self, obj):
        return [choice[0] for choice in Todo.priority_choices]

    class Meta:
        model = Todo
        fields = ('id', 'title', 'description', 'completed', 'priority', 'priority_choices')

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

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