简体   繁体   中英

Django Rest Framework - define required fields

EDIT

I just want to raise exception when I do BrokerSerializer(user).data and any of values is None

I'm using DRF to serialize objects to export them through API, I don't use it to creating objects.

Looking for a simplest way to make fields required when serializing model.

The API needs some fields to be not null so I want to raise APIMissingDataException if any of them is null/None.

I tried:

class BrokerSerializer(serializers.ModelSerializer):
    import_id = serializers.IntegerField(source='pk')
    deleted = serializers.SerializerMethodField()
    full_name = serializers.CharField(source='userprofile.get_display_name')
    phone_work = serializers.CharField(source='userprofile.contact_information.telephone')
    email_work = serializers.CharField(source='userprofile.contact_information.email')

class Meta:
    model = User
    fields = ['import_id', 'deleted', 'full_name', 'phone_work', 'email_work']
    required_fields = fields


def validate(self, attrs):
    super().validate(attrs)
    if not all([attrs.get(fieldname) for fieldname in self.Meta.required_fields]):
        raise APIMissingDataException()
    return attrs

def get_deleted(self, obj):
    return 0

But validate function is not being called for some reason. I don't want to explicitely defining all fields just to add required=False parameters to them.

In [10]: b = BrokerSerializer(User.objects.first())                                                                                                                                                  

In [11]: b.data                                                                                                                                                                                       

# It should have raised exception since there are None
Out[11]: {'import_id': 1, 'deleted': 0, 'full_name': None, 'phone_work': None, 'email_work': None}

In [12]: b = BrokerSerializer(data=User.objects.first())                                                                                                                                             

In [13]: b.is_valid()                                                                                                                                                                                
Out[13]: False

In [14]: b.data                                                                                                                                                                                      
Out[14]: {}

Is there a more comfortable way?

I hope this answer is also applicable here :)

Summary
The validation process undergoes only while Deserialization process (input is a dict like object) and you are trying a Serialization process . In the case of Serialization , DRF assumes the given object is a valid one and hence it doesn't require validation.

DRF has builtin methods to handle it.

name = serializers.CharField(label="name field",required=True, allow_blank=False, allow_null=False)

Then use serializer.is_valid() to validate the data.

For more details, refer to this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM