Tastypie with ImageKit relationship

160 views Asked by At

Consider these pseudo models:

class Product:
    name = charfield

class ProductImage:
    image = foreignKey(Product)

And this resource

class ProductResource(ModelResource):
    images = fields.RelatedField('path.to.resources.ProductImageResource', 'images__all', full=True)

    class Meta:
        queryset = Product.objects.all()
        resource_name = 'products'

The returning JSON is:

{

    "meta": { ... },
    "objects": [
        {
            "name": "Test",
            "images": "[<ProductImage: ProductImage object>, <ProductImage: ProductImage object>]",
        }
    ]

}

Offcourse this is rather useless, I just need to list some attribute of the instances. Is this only possible with the dehydrate approach:

def dehydrate(self, bundle):
    bundle.data['images'] = list()
    for x in ProductImage.objects.filter(base_product__id=bundle.data['id']):
        bundle.data['images'].append(x.thumbnail)
    return bundle
1

There are 1 answers

1
DJ_HOEK On

Did you try defining a unicode definition for your ProductImage, so it prints the attribute you desire, instead of "ProductImage: ProductImage object"?