枚举Django Rest Framework序列化器中的模型选择 [英] Enumerating model choices in a Django Rest Framework serializer

查看:141
本文介绍了枚举Django Rest Framework序列化器中的模型选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Django选择字段的模型,如下所示:

I have a model that uses a Django choices field, like this:

class Question(models.Model):
QUESTION_TYPES = (
    (10,'Blurb'),
    (20,'Group Header'),
    (21,'Group Footer'),
    (30,'Sub-Group Header'),
    (31,'Sub-Group Footer'),
    (50,'Save Button'),
    (100,'Standard Question'),
    (105,'Text-Area Question'),
    (110,'Multiple-Choice Question'),
    (120,'Standard Sub-Question'),
    (130,'Multiple-Choice Sub-Question')
)
type = models.IntegerField(default=100,choices=QUESTION_TYPES)

我正在使用Django Rest Framework将此模型作为API展示给Angular Web应用.在我的Angular Web应用程序中,我想要一个组合框窗口小部件,它会下拉所有这些选择.不是整数,而是文本选择,例如模糊",标准问题"等等.

I'm using Django Rest Framework to present this model as an API to an Angular web app. In my Angular web app, I want a combo box widget that drops down with all those choices. Not the integers, but the text choices, like "blurb", "standard question" and so on.

现在,我可以将组合框编码到Angular应用程序中,但是本着DRY的精神,有可能编写一个仅返回这些选择的DRF序列化程序(即QUESTION_TYPES对象),以便我可以填充组合框带有ReST查询的框?

Now, I could hand code the combo box into the Angular app, but in the spirit of DRY, is it possible to write a DRF serializer that just returns those choices (ie the QUESTION_TYPES object), so I can populate the combo box with a ReST query?

可能"一词,我想我的意思是简单而优雅".也许我也说"ReSTful". (这样做是否很有趣?)

And by "possible", I guess I mean "simple and elegant". And maybe I also mean "ReSTful". (Is it ReSTful to do it that way?)

只是想知道. .

谢谢

约翰

推荐答案

我可能会尝试以下操作:

I would probably try something like the following:

# models.py
class Question(models.Model):
    QUESTION_NAMES = (
        'Blurb',
        'Group Header',
        'Group Footer',
        'Sub-Group Header',
        'Sub-Group Footer',
        'Save Button',
        'Standard Question',
        'Text-Area Question',
        'Multiple-Choice Question',
        'Standard Sub-Question',
        'Multiple-Choice Sub-Question')
    QUESTION_VALS = (10, 20, 21, 30,
                     31, 50, 100, 105, 110,
                     120, 130)
    QUESTION_TYPES = tuple(zip(QUESTION_VALS, QUESTION_NAMES))
    # Personal choice here: I never name attribs after Python built-ins:
    qtype = models.IntegerField(default=100,choices=QUESTION_TYPES)


以下内容无法正常运行

(以下是我最初对序列化对象列表的直觉,但没有用.无论如何,我还是将其留在这里,因为它似乎应该可以使用.)

(Following was my original intuition on serializing a list of objects, but it did not work. I'm leaving it in here anyway, because it seems like it should work.)

好的,所以我们有一种方法可以自行访问字符串,现在只需要序列化它们,为此,我可能会尝试使用ListField

Okay, so we have a way to access the strings on their own, now we just need to serialize them, and for that, I'd probably try to use the ListField in DRF3, which should support the source kwarg, I would think?

# serializers.py
from .models import Question
class YourSerializer(ModelSerializer):
    names = serializers.ListField(
       child=serializers.CharField(max_length=40),
       source=Question.QUESTION_NAMES
    )
    class Meta:
        model = Question
        fields = ('names', etc.)


以下内容确实返回结果列表

回扣:使用SerializerMethodField:

from .models import Question

class YourSerializer(serializers.ModelSerializer):
    ...
    names = serializers.SerializerMethodField()

    def get_names(self, obj):
        return Question.QUESTION_NAMES

    class Meta:
        model = Question

演示:

In [1]: q = Question.objects.create()
Out[1]: <Question: Question object>  

In [2]: ser = YourSerializer(q)

In [3]: ser.data
Out[3]: {'id': 1, 'names': ['Blurb', 'Group Header', 'Group Footer', 'Sub-Group Header', 'Sub-Group Footer', 'Save Button', 'Standard Question', 'Text-Area Question', 'Multiple-Choice Question', 'Standard Sub-Question', 'Multiple-Choice Sub-Question'], 'qtype': 100}

这篇关于枚举Django Rest Framework序列化器中的模型选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆