How can I combine multiple Resources in TastyPie? I have 3 models I’d like to combine: users, profiles and posts.
Ideally I’d like profiles nested within user. I’d like to expose both the user and all of the profile location from UserPostResource. I’m not sure where to go from here.
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
fields = ['username','id','date_joined']
#Improper Auth
authorization = Authorization()
class UserProfileResource(ModelResource):
class Meta:
queryset = UserProfile.objects.all()
resource_name = 'profile'
class UserPostResource(ModelResource):
user = fields.ForeignKey(UserResource,'user', full=True)
class Meta:
queryset = UserPost.objects.all()
resource_name = 'userpost'
#Improper Auth
authorization = Authorization()
Here are my models:
class UserProfile(models.Model):
user = models.OneToOneField(User)
website = models.CharField(max_length=50)
description = models.CharField(max_length=255)
full_name = models.CharField(max_length=50)
class UserPost(models.Model):
user = models.ForeignKey(User)
datetime = models.DateTimeField(auto_now_add=True)
text = models.CharField(max_length=255, blank=True)
location = models.CharField(max_length=255, blank= True)
Tastypie fields (when the resource is a
ModelResource) allow passing in theattributekwarg, which in turn accepts regular django nested lookup syntax.So, first of all this might be useful:
and given the above change, the following:
will expose the data from
UserProfilemodel within theUserResource.Now if you’d like to expose a list of locations (coming from
UserPost) within theUserResourceyou will have to override one ofTastypiemethods. According to the documentation a good candidate would be thedehydrate()method.Something like this should work: