Search code examples
pythondjangodjango-rest-frameworkdjango-serializer

How Do I access Object and serializer Value in same Validate function?


I have following model

class Search(models.Model):
   trip_choice = (
        ('O', 'One way'),
        ('R', 'return')
    )
    booking_id = models.IntegerField(db_index=True, unique=True)
    trip_type = models.CharField(max_length=20, choices=trip_choice)

and Booking Moddel is Fk with search

class Booking(models.Model)
    flight_search = models.ForeignKey(Search, on_delete=models.CASCADE)
    flight_id = models.CharField(
        max_length=100
    )
    return_id = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )

I have following rule if trip type is Return 'R' the return id cannot be sent empty in serializer.

class AddBookSerializer(BookSerializer):
    class Meta(BookSerializer.Meta):
        fields = (
            'flight_search',
            'flight_id',
            'return_id',
        )

    def validate_flight_search(self, value):
         print(value.trip_type)

I want to access and check return_id and if it is empty Validation error is to be raised I dont know how I shall proceed as value.trip_type give me R but I cannot compare that with return id.


Solution

  • If you want to validate the value of one argument based on another value, you can do that in validate method.

    class AddBookSerializer(serializers.ModelSerializer):
        def validate(self, attrs):
            trip_type = attrs['flight_search'].trip_type
            return_id = attrs.get('return_id', None)
            if trip_type == 'R' and not return_id:
                raise serializers.ValidationError("blah")
            return attrs
    

    Bonus points for using TextChoices instead of a tuple.