Dynamic Choices for ChoiceField

459 views
Skip to first unread message

Jay McEntire

unread,
Apr 9, 2015, 4:49:18 PM4/9/15
to django-res...@googlegroups.com
Prior to DRF 3.x this code worked:

class HostCreateUpdateSerializer(serializers.Serializer):
    expire_days = serializers.ChoiceField(required=False)
    network = serializers.ChoiceField(required=False)
    pool = serializers.ChoiceField(required=False)
    dhcp_group = serializers.ChoiceField(required=False)

     def __init__(self, *args, **kwargs):
        super(HostCreateUpdateSerializer, self).__init__(*args, **kwargs)
        blank_choice = [('', '-------------')]
        self.fields['expire_days'].choices = blank_choice + [(expire.expiration.days, expire.expiration.days) for expire in ExpirationType.objects.all()]
        self.fields['network'].choices = blank_choice + [(network.network, network.network) for network in Network.objects.all()]
        self.fields['pool'].choices = blank_choice + [(pool.name, pool.name) for pool in Pool.objects.all()]
        self.fields['dhcp_group'].choices = blank_choice + [(dhcp_group.pk, dhcp_group.name) for dhcp_group in DhcpGroup.objects.all()]



Now in DRF 3.x the choices attribute is required.  I can set it to an empty list, but I need to be able to populate choices dynamically.  If I populate them on declaration, they become cached and any changes to my database will not be picked up.  This code doesn't work in 3.x anymore.  It appears that fields are getting initialized differently now.

Thanks for any help you an provide.

-J

Reply all
Reply to author
Forward
0 new messages