django rest framwork iterate throug fields in mode

2019-06-06 10:44发布

i want to iterate through the fields in ModelSerializer and want to make those field required . this not working . how can i do that. Somebody please help me.

class CustomerSerializer(serializers.ModelSerializer):

    class Meta:
        model = Customer

        fields = ("email", "phone_no", "full_name", "landline_no")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for field in self.fields:
            self.fields[field].required = True
            self.fields[field].allow_blank = False

1条回答
Bombasti
2楼-- · 2019-06-06 10:59

You can add the extra args in Meta class for a ModelSerializer, like this:

class Meta:
    model = Customer

    fields = ("email", "phone_no", "full_name", "landline_no")
    extra_kwargs = {'email': {'required': True, 'allow_blank': False}}

If you need this for all the fields, then you should reconsider your fields inside the Customer model. You can add blank=False and/or null=False. Rest framework takes that information into consideration when creating a ModelSerializer

查看更多
登录 后发表回答