1

I have a model with custom "ArrayField" (for a Postgres array field), which stores an array of foreign keys to another model. Django doesn't enforce the relation, but what I put in there are foreign keys.

class Foo(model):
    bars  =  ArrayField(models.IntegerField())

class Bar(model):
    blah  = models.CharField()

So the value of the 'bars' field is like [3,64,7,34,...] where the numbers are non-enforced foreign keys to Bar. When rendering Foos, I'd like to render the related objects represented in this field using Django REST Framework:

{ "foo" : {  "bars" : [ {"blah":"asdf"},
                        {"blah":"asdf"}
                      ]
          }
}

I'm having trouble figuring out how that should be expressed in the serializer:

class BarSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ('blah')

    blah     = serializersCharField()


class FooSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ('bars')

    # bars     = BarSerializer(many=True)
    bars      = SomeSpecialCustomField() #?

How can I get JSON as above when rendering?

1 Answer 1

1

Try playing around with this:

class SomeSpecialCustomField(serializers.Field):

    def to_native(self, value):
        queryset = Bar.objects.filter(pk__in=value)
        serializer = BarSerializer(queryset, many=True)
        return serializer.data

Make sure you put proper validations, like checking if the value is a list etc.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.