evenicoulddoit / django-rest-framework-serializer-extensions

Extensions to help DRY up Django Rest Framework serializers
Other
247 stars 23 forks source link

Unable to access related object specified in expandable_fields from serializer #45

Closed rldiao closed 3 years ago

rldiao commented 3 years ago

Hi,

I'm currently using this library with DRF 3.12 and trying to perform some validations in the serializer by checking a related object.

Something like this:

class FooSerializer(SerializerExtensionsMixin, serializers.ModelSerializer):
    class Meta:
        model = Foo
        expandable_fields = dict(
          bar=BarSerializer,
        )

   def validate(self, data):
        try:
            # For POST
            bar = data['Bar']
        expect KeyError:
            # For PATCH
            bar = self.instance.bar
        if bar.time < datetime.now():
            raise ValidationError()
        return data

This code works when Bar is specified in fields but not expandable_field. Just asking if the object is stored somewhere where I can assess?

Thanks

evenicoulddoit commented 3 years ago

Hey! I'm just trying to understand the use case, but also looking at the code sample I see the Bar is title-cased in one instance. Am I just to assume that this is a typo in your example, and not the cause of your problem?

rldiao commented 3 years ago

Yeah that would just be a typo. I'm basically trying validate if you can create or update the object based on a related object's field.

So in the case of you trying to change foo but now() is greater than bar.time, then validate will raise a ValidationError

evenicoulddoit commented 3 years ago

And have you seen the writable foreign keys section, here?

rldiao commented 3 years ago

After some thought, I've decided to pursue a different solution to my problem. Thanks for the support