Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 带有动态选项的Django Rest框架MultipleChiceField_Python_Django_Django Rest Framework - Fatal编程技术网

Python 带有动态选项的Django Rest框架MultipleChiceField

Python 带有动态选项的Django Rest框架MultipleChiceField,python,django,django-rest-framework,Python,Django,Django Rest Framework,所以我刚开始使用Django Rest框架,我的一个序列化程序有一个multipleEchoiceField,其中的选项只是另一个模型的所有实例 下面是有问题的序列化程序: class ObjectTypeSerializer(serializers.ModelSerializer): def get_field_choices(): return sorted([ (p.id, p.name) for p in Parameter.object

所以我刚开始使用Django Rest框架,我的一个序列化程序有一个multipleEchoiceField,其中的选项只是另一个模型的所有实例

下面是有问题的序列化程序:

class ObjectTypeSerializer(serializers.ModelSerializer):

    def get_field_choices():
        return sorted([
            (p.id, p.name) for p in Parameter.objects.all()
        ])

    object_fields = serializers.MultipleChoiceField(
        choices=get_field_choices()
    )

    instance_fields = serializers.MultipleChoiceField(
        choices=get_field_choices()
    )

    labels = serializers.SlugRelatedField(
        queryset=Label.objects.all(),
        many=True, allow_null=True, slug_field='name'
    )

    class Meta:
        model = ObjectType
        fields = ('id', 'name', 'object_fields',
                    'instance_fields', 'labels')
但是,当我添加一个新的参数对象时,这些选项不会更新。在常规的Django表单中,我只需使用

forms.ChoiceField(choices=[(p.id, p.name) for p in Parameter.objects.all()]) 
当添加新参数时,它将更新选项,而无需重新启动服务器。如何使用Django Rest框架序列化程序实现同样的功能


感谢您的帮助。谢谢

当您的选择是模型时,最直接的方法是使用
RelatedField
的一些导数。考虑到您正在使用
p.id
PrimaryKeyRelatedField
是否适合您?(如果没有,请更新您的问题)

如果默认行为(使用模型的
\uuuuu unicode\uuuuu
作为显示值)不是您想要的,则始终可以对其进行子类化,并重新定义
显示值
方法:

class CustomPKRelatedField(serializers.PrimaryKeyRelatedField):
    """A PrimaryKeyRelatedField derivative that uses named field for the display value."""

    def __init__(self, **kwargs):
        self.display_field = kwargs.pop("display_field", "name")
        super(CustomPKRelatedField, self).__init__(**kwargs)

    def display_value(self, instance):
        # Use a specific field rather than model stringification
        return getattr(instance, self.display_field)

...
class ObjectTypeSerializer(serializers.ModelSerializer):
    ...
    object_fields = CustomPKRelatedField(queryset=Parameter.objects.all(), many=True)
    instance_fields = CustomPKRelatedField(queryset=Parameter.objects.all(), many=True)
    ...
...
如果您所需要的只是浏览,那么LeapInderer将呈现一个漂亮的
,我相信这就是您所需要做的


ChoiceField
multipleechoicefield
设计用于静态数据集。他们甚至在
\uuuuu init\uuuuu
中对事物进行预处理,以允许分组。这就是为什么新项目不会出现在那里——这些字段本质上永远“缓存”结果(直到服务器重新启动)

如果出于某种原因,您真的需要它是
ChoiceField
-派生的,您可以设置
post\u save
post\u delete
信号侦听器和更新字段的
选项
(如果您不是在一个已经包含a的非常先进的版本上,则可以设置
grouped\u选项
)属性。有关详细信息,请查看
选项字段
。不过,那将是一次卑鄙的攻击