2
votes

i'm trying to get nested object fields populated, however the only thing being returned is the primary key of each object (output below):

{
    "name": "3037",
    "description": "this is our first test product",
    "components": [
        1,
        2,
        3,
        4
    ]
}

How do I have the component model's fields populated as well (and not just the PKs)? I would like to have the name and description included.

models.py

class Product(models.Model):
    name = models.CharField('Bag name', max_length=64)
    description = models.TextField ('Description of bag',  max_length=512, blank=True)
    urlKey = models.SlugField('URL Key', unique=True, max_length=64)  
    def __str__(self):
        return self.name

class Component(models.Model):
    name = models.CharField('Component name', max_length=64)
    description = models.TextField('Component of product',  max_length=512, blank=True)
    fits = models.ForeignKey('Product', related_name='components')
    def __str__(self):
        return self.fits.name + "-" + self.name 

serializers.py

from rest_framework import serializers
from app.models import Product, Component, Finish, Variant

class componentSerializer(serializers.ModelSerializer):
    class Meta:
    model = Component
    fields = ('name', 'description', 'fits')

class productSerializer(serializers.ModelSerializer):
    #components_that_fit = componentSerializer(many=True) 
    class Meta:
        model = Product
        fields = ('name', 'description', 'components')
        #fields = ('name', 'description', 'components_that_fit' )

The documented approach doesn't seem to be working for me, and gives me the following error (you can see the lines following the standard approach commented out in the serializers.py entry above:

Got AttributeError when attempting to get a value for field 'components_that_fit' on serializer 'productSerializer'. The serializer field might be named incorrectly and not match any attribute or key on the 'Product' instance. Original exception text was: 'Product' object has no attribute 'components_that_fit'.

Update based on answer

Thanks to @Carlton's answer below, here's what is working for me: serializers.py was changed and now looks like this:

class productSerializer(serializers.ModelSerializer):
    components = componentSerializer(many=True)
    class Meta:
        model = Product
        fields = ('name', 'description', 'components')
1

1 Answers

2
votes

By calling the field components_that_fit, you're having the serialiser look for an attribute by that name. (There isn't one, hence your error.)

Two ways to fix it:

  • Call the field components, but declare it as components = componentSerializer(many=True)
  • Set source='components' field option when declaring the components_that_fit field.

The reason you get primary keys is that, unless declared explicitly, relations default to PrimaryKeyRelatedField.

I hope that helps.