django - DRF : callable in serializer choicefield "choices"

标签 django django-rest-framework

我有一个带有“所有者”字段的管理序列化程序。我希望当前用户填充此字段的选择,但在运行迁移时我收到 TypeError,表明 drf 不支持序列化器选择字段的可调用项。 django 支持模型选择字段的可调用项,但显然用户会随时更改,因此我希望在序列化器实例化时填充该字段。有人可以在这里提出可行的解决方案吗?

def get_available_users():
    return [(u.id, u.username) for u in User.objects.all()]


class AdminCreateSerializer(CreateSerializer, AdminSerializer):
    owner = serializers.ChoiceField(choices=get_available_users)


>> TypeError: 'function' object is not iterable

最佳答案

让您的迁移发挥作用

添加

from django.utils.functional import lazy

然后

owner = serializers.ChoiceField(choices=lazy(get_available_users, tuple)())

def get_available_users():
    try:
        _users = [(u.id, u.username) for u in User.objects.all()]
    except:
        _users = list(tuple())
    return _users

关于django - DRF : callable in serializer choicefield "choices",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50673949/

相关文章:

python - 在DeleteView中标记为已删除而不是实际删除

nested - 预期实例,获得 OrderedDict Django Rest Framework 可写嵌套序列化器

python - Django Rest Framework - 嵌套序列化程序是延迟加载的吗?

python - django 剥离/删除/清除值

用于 View 的 python 日志记录装饰器

python - Django 根据字段值过滤

Django API 在本地工作,但在 Elastic Beanstalk 上部署时不起作用

python - 如何反序列化 django rest 框架中的多个对象列表?

python - django unique together 不适用于 none datetime

python - Django 1.6 : MySQL ERROR 1049 (42000): Unknown database