Santana
Santana

Reputation: 175

django tastypie include def from model as one of attribute on a resource

I have:

class Item(models.Model):
    # some fields like name,  quantity

    def get_first_image(self):
        instance = ItemImage.objects.filter(parent_id = self.id)[0]
        return instance.images

class ItemImage(models.Model):
    # parent with foreignkey to Item and an ImageField to store images

How can I retrieve the value of get_first_image using tastypie?

Upvotes: 0

Views: 118

Answers (1)

Ngure Nyaga
Ngure Nyaga

Reputation: 3027

You could try using custom Resources with per-field dehyration for the fields that you want to "synthesize" eg

# Imports etc omitted

class ItemResource(ModelResource):
    # some fields like name,  quantity
    first_image = fields.ImageField(readonly=True)

    def dehydrate_first_image(self):
        instance = ItemImage.objects.filter(parent_id = self.id)[0]
        return instance.images

You can get more information on resources in the tastypie resources documentation

This "per field dehydrate", coupled with a read-only field like the one you have above should do it.

Upvotes: 1

Related Questions