Paras
Paras

Reputation: 3471

How to apply partial validation in Django Models on a REST API

I'm getting started with building REST API with Django using DRF. I get that there are default validations that can be applied to fields while definig a Model class.

I need to know, what should be a good approach for defing a partial validation for field.

Let us consider the following Model CLass :

class Test(models.Model):
   a = models.CharField("A", max_length=100)    
   b = models.TextField("B", blank=True, null=True)
   c = models.TextField("C", null=True, blank=True) 

Now for field a it is a required field which is what I need, for the fields b and c, I want that either of one should be present always, that is if b is present c can be null or empty and vice-a-versa.

So I read that I can write the serializer and wireup the validation code within it, also I can define a clean method within my model to provide the validation logic.

Can someone provide me an example?

Upvotes: 0

Views: 404

Answers (2)

ruddra
ruddra

Reputation: 51938

I think you can use validate Method:

class MySerializer(serializers.ModelSerializer):

    def validate(self, data):            
        if data.get('c') or data.get('b'):
            return data
        raise serializers.ValidationError("Provide B or C")

Upvotes: 1

aman kumar
aman kumar

Reputation: 3156

serializer have the get fields method where you can do the operations

class Test(serializer.Srailizers):
   a = serializer.CharField()    
   b = serializer.TextField()
   c = serializer.TextField()

   def get_fields(self):
      fields = super().get_fields()
      # check you logic here and make change
      fields['b'].required = False
      return fields

Upvotes: 0

Related Questions