Giri
Giri

Reputation: 31

How to combine mutiple resources in django-tastypie?

Lets say I have three models Submission, Contact and SubmissionContact.

class Submission(models.Model):
  title = models.CharField(max_length=255, verbose_name='Title')
  ...

class Contact(models.Model):
  name = models.CharField(max_length=200, verbose_name='Contact Name')
  email = models.CharField(max_length=80, verbose_name='Contact Email')
  ...

class SubmissionContact(models.Model):
  submission = models.ForeignKey(Submission)
  contact = models.Foreign(Contact, verbose_name='Contact(s)')

Can I read / write to all these three tables using a single ModelResource using tastypie. (basically get and put actions on list and detail in tastypie)

Thanks in advance for any help.

Upvotes: 3

Views: 2735

Answers (1)

Hedde van der Heide
Hedde van der Heide

Reputation: 22449

You can nest one model into the other or use the dehydrate cycle to add extra resources to your output, for example consider a Foo and Bar model

class FooResource(ModelResource):
    class Meta:
        queryset = Foo.objects.all()
        resource_name = 'foo'
        serializer = Serializer(formats=['xml', 'json'])
        excludes = ['date_created']

class BarResource(ModelResource):
    foo = fields.ForeignKey(FooResource, attribute='foo', full=True, null=True)

    class Meta:
        queryset = Bar.objects.all()
        resource_name = 'bar'
        serializer = Serializer(formats=['xml', 'json'])

If there's no relationship you could also do something like (with large datasets this would cause a lot of database overhead, you might have to rethink your model definitions):

class FooResource(ModelResource):
    class Meta:
        queryset = Foo.objects.all()
        resource_name = 'foo'
        serializer = Serializer(formats=['xml', 'json'])
        excludes = ['date_created']

    def dehydrate(self, bundle):
        obj = self.obj_get(id=bundle.data['id'])
        bundle.data['bar'] = Bar.objects.get(id=1).name
        return bundle

Upvotes: 4

Related Questions