Add Serializer on Reverse Relationship - Django Rest Framework
<p>I have a <code>Cart</code> model and a <code>CartItem</code> model. The <code>CartItem</code> model has a <code>ForeignKey</code> to the <code>Cart</code> model.</p>

<p>Using Django Rest Framework I have a view where the API user can display the <code>Cart</code>, and obviously then I want to include the <code>CartItem</code> in the respone. </p>

<p>I set up my Serializer like this:</p>

<pre><code>class CartSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    cartitem_set = CartItemSerializer(read_only=True)
    class Meta:
        model = Cart
        depth = 1
        fields = (
            'id', 
            'user', 
            'date_created', 
            'voucher', 
            'carrier', 
            'currency', 
            'cartitem_set', 
        )
</code></pre>

<p>My problem is the second line, <code>cartitem_set = CartItemSerializer(read_only=True)</code>.</p>

<p>I get AttributeErrors saying <code>'RelatedManager' object has no attribute 'product'</code>.  ('product' is a field in the <code>CartItem</code> model. If I exclude product from the <code>CartItemSerializer</code> I just get a new AttributeError with the next field and so on. No matter if I only leave 1 or all fields in the Serializer, I will get a error.</p>

<p>My guess is that for some reason Django REST Framework does not support adding Serializers to reverse relationships like this. Am I wrong? How should I do this?</p>

<p>PS</p>

<p>The reason why I want to use the <code>CartItemSerializer()</code> is because I want to have control of what is displayed in the response.</p>