[Solved]-Validation in patch method in django rest framework

11👍

Use self.partial in the validate method to find out if it’s a partial update.

def validate(self, data):
    if self.partial:
        print("Partial update")
    return data

0👍

you can define validate_< field_name > method to validate specific field, in this way if the field is included in request data, it will be validated; otherwise it will not be validated.

For example:

def validate_year_start(self, value):
    year_start  = value
    request     = self._context["request"]
    user_dob    = request.user.dob
    age         = request.user.age

    current_time = datetime.datetime.now()
    if not user_dob:
        user_dob = relativedelta(current_time, years=age)

    if year_start < user_dob.year:
        raise serializers.ValidationError({"year_start":"Year-start can't be before user's DOB"})
    return value
👤Emma

Leave a comment