gpt4 book ai didi

python - Django Rest Framework ParentRelatedField 元数据选择

转载 作者:行者123 更新时间:2023-11-28 17:15:07 25 4
gpt4 key购买 nike

大家好!

我有最新的 django-rest-framework,我正在尝试让序列化程序在 OPTIONS 请求中显示每个字段的可能选择。

这是我模型的一部分

# models.py
class Task(models.Model):
parent = models.ForeignKey('self',
blank=True, null=True, related_name='child_tasks')
title = models.CharField(max_length=128)
status = models.CharField(max_length=16, choices=STATUS_CHOISES, default='new')
priority = models.CharField(max_length=16, choices=PRIORITY_CHOISES, default='1')
chief = models.ForeignKey('users.SystemUser', related_name='tasks',
blank=True, null=True)

这是序列化器

# serializers.py
class ParentRelatedField(serializers.PrimaryKeyRelatedField):
def get_queryset(self):
obj = self.context['view'].get_object()
return Task.objects.exclude(pk=obj.pk)


def get_user_choices():
return tuple([(i.id, i.system_name) for i in SystemUser.objects.all()])


class TaskDetailSerializer(serializers.Serializer):
title = serializers.CharField()
parent = ParentRelatedField(
required=False, allow_null=True
)
status = serializers.ChoiceField(choices=STATUS_CHOISES)
priority = serializers.ChoiceField(choices=PRIORITY_CHOISES)
chief = serializers.ChoiceField(choices=get_user_choices(), required=False)

我使用 get_user_choices 函数实现了 chief 字段,所以我得到:

"chief": {
"type": "choice",
"required": false,
"read_only": false,
"label": "Chief",
"choices": [
{
"value": 1,
"display_name": "First User Name"
}
]
}

ParentRelatedField 非常适合验证,但不适用于元数据:

"parent": {
"type": "field",
"required": false,
"read_only": false,
"label": "Parent"
}

我不能将 ChoiceField 与函数一起使用(如在 chief 中),因为 parent 选择必须排除当前 Task 对象。

最佳答案

解决了问题。

解决方案位于 drf 3.4 announcementdrf issue comments .

我改变了我的领域,让它更通用

class SelfExcludingRelatedField(serializers.PrimaryKeyRelatedField):
def get_queryset(self):
obj = self.context['view'].get_object()
return self.queryset.exclude(pk=obj.pk)

然后编写自定义元数据类(从github复制)。

class CustomMetadata(SimpleMetadata):
def get_field_info(self, field):
field_info = super().get_field_info(field)

if (not field_info.get('read_only') and
isinstance(field, SelfExcludingRelatedField) and
hasattr(field, 'choices')):
field_info['choices'] = [
{
'value': choice_value,
'display_name': choice_name
}
for choice_value, choice_name in field.choices.items()
]

return field_info

并将其添加到设置:

REST_FRAMEWORK = {
'DEFAULT_METADATA_CLASS': 'api_v0.metadata.CustomMetadata',
}

关于python - Django Rest Framework ParentRelatedField 元数据选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44760047/

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