Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRF: callable in serializer choicefield "choices"

I have an admin serializer with an 'owner' field. I want the current users to populate the choices of this field, but when it comes to running migrations I get a TypeError, suggesting that drf doesnt support callables for the serializer choice field. django supports callables for the model choices field, but obviously the users change on the time, so I want this field to be populated on the serializer instantiation. Can anyone suggest a workable solution here?

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
like image 657
Liz Avatar asked Jun 04 '18 05:06

Liz


1 Answers

To get your migrations to work

add

from django.utils.functional import lazy

then

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

or

def get_available_users():
    try:
        _users = [(u.id, u.username) for u in User.objects.all()]
    except:
        _users = list(tuple())
    return _users
like image 97
beautiful.drifter Avatar answered Oct 09 '22 02:10

beautiful.drifter