[Answered ]-Django (DRF) select related on is_valid()?

0👍

The way I solved it was I took the direction athanasp pointed me in and tweaked it a bit as his solution was close but not working entirely.

I:

  1. Created a simple nested serializer
  2. Used the init-method to make the query
  3. Each item checks the list of companies in its own validate method
class CitySerializer(serializers.ModelSerializer):
        class Meta:
        model = City
        fields = ('name',)
class ListingSerializer(serializers.ModelSerializer):
    # city = serializers.IntegerField(required=True, source="city_id") other alternative
    city = CitySerializer()

     def __init__(self, *args, **kwargs):
          self.cities = City.objects.all()
          super().__init__(*args, **kwargs)

    def validate_city(self, value):
    try:
        city = next(item for item in self.cities if item.name == value['name'])
    except StopIteration:
        raise ValidationError('No city')
    return city

And this is how the data looks like that should be added:

city":{"name":"stockhsdolm"}

Note that this method more or less works using the IntegerField() suggested by athan as well, the difference is I wanted to use a string when I post the item and not the primary key (e.g 1) which is used by default.
By using something like
city = serializers.IntegerField(required=True, source="city_id") works as well, just tweak the validate method, e.g fetching all the Id’s from the model using values_list(‘id’, flat=True) and then simply checking that list for each item.

1👍

Have you tried to define company as IntegerField in the serializer, pass in the view’s context the company IDs and add a validation method in field level?

class ActiveApartmentSerializer(serializers.ModelSerializer):
    company = serializers.IntegerField(required=True)

    ...

    def __init__(self, *args, **kwargs):
        self.company_ids = kwargs.pop('company_ids', None)
        super().__init__(*args, **kwargs)
   
    def validate_company(self, company):
        if company not in self.company_ids:
            raise serializers.ValidationError('...') 
        return company  

Leave a comment