Thomas K
Thomas K

Reputation: 35

How to get TastyPie fields.foreignkey to only return certain fields as apposed to resource uri or full object

I have a TastyPie resource setup to return all Quotes from the database. Each quote has a foreign key relationship to a Django user.

class QuoteResource(ModelResource):
    user = fields.ForeignKey(UserResource, 'user')

class Meta:
    queryset = Quote.objects.all().order_by('-created')
    limit = 0
    max_limit = 0
    resource_name = 'quotesreport'
    allowed_methods = ['get']
    authentication = BasicAuthentication()
    authorization = DjangoAuthorization()
    always_return_data = True

def dehydrate(self, bundle):
    return bundle

This returns the quote with user set to a resource uri, which is mostly unhelpful to me for what I am trying to accomplish.

I attempted to set full=True on user, but this unfortunately kills response time to an unusable level, and puts too much on the server as there are 4k+ results and growing every day.

Ideally I would like:

bundle.data['user'] = "%s %s" % (user.first_name, user.last_name)

Is there a way that I have been unable to find to get this seemingly simple task done?

Upvotes: 0

Views: 639

Answers (1)

dan-klasson
dan-klasson

Reputation: 14210

What's wrong with bundle.data['user'] = "%s %s" % (user.first_name, user.last_name)?

You could also check out this base class that I wrote. With it you can specify what fields to fetch:

https://github.com/dan-klasson/django-tastypie-specified-fields

Upvotes: 1

Related Questions