Juanma Jurado
Juanma Jurado

Reputation: 574

Dehydrate a tastypie class with data from a related resource?

I am creating an API with tasstypie and I want to retreive a user nick in a comment resource. The comment resource send the user_uri, but I can't dehydrate the info to add also the name of the user.

The models are:

class User(models.Model):
    nick = models.CharField(max_length = 255)

class Comment(models.Model):
    name = models.CharField(max_length = 511)
    user = models.ForeignKey(User, related_name='comments')

The tastypie api is:

class CommentResource(ModelResource):
    user = fields.ToOneField(UserResource, 'user')


class Meta:
    queryset = Comment.objects.all()
    resource_name = 'comment'
    serializer = Serializer(formats=['json'])
    allowed_methods = ['get']
    always_return_data=True

def dehydrate(self, bundle):
    bundle.data['nick_user'] = #here I want to send user nick
    return bundle

this get the uri from the UserResource in a 'user' variable. How I can access to the user nick from the dehydrate method from CommentResource?

Thanks

Upvotes: 0

Views: 2575

Answers (1)

Alex Botev
Alex Botev

Reputation: 1399

Why instead of touching the whole dehydrate method you don't use dehydrate_user(self, bundle) and return bundle.obj.nick?

Upvotes: 1

Related Questions