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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With