tastypie - Getting from ToManyField to Model values -
in django, have 2 models - user , userprofile. there may exist 0 or 1 profiles particular user. i'm trying include information userprofile model directly on userresource.
i use profile tomanyfield, if exists, access contents of associated userprofile model. i've tried variety of things in dehydrate, including self.profile.get_related_resource(self) , userprofile.objects.get(id=...), can't seem find way profile field model object. can me out?
i'm still new python, django, , tastypie, if i'm doing awful kind enough point out.
the goal have json looks this: { resourceuri: /v1/users/1 date_of_birth: jan 1, 1980 ... etc }
where date_of_birth property of userprofileresource. don't want of fields userprofileresource, , don't want userprofile nested object in response - want fields userprofileresource top-level fields in response, part of user resource.
class userresource(modelresource): profile = fields.toonefield('foo.api.userprofileresource', 'user', null=true) class meta: queryset = user.objects.all() resource_name = 'users' allowed_methods = ['get'] #etc... class userprofileresource(modelresource): date_of_birth = ... #etc
i assume you're using django 1.4 , auth_profile_module
?
since user:userprofile relationship 1:1 opt toonefield instead. serialize uri pointer userprofileresource (if 1 exists.) if you'd userprofileresource field data inline userresource, can specify full=true
in toonefield definition. method should not need override dehydrate.
also, ensure second argument in toonefield definition user attribute points userprofile django model. example if have onetoonefield(user, related_name='profile')
in django model attribute should profile
.
class userresource(modelresource): profile = fields.toonefield('foo.api.userprofileresource', 'profile', full=true, null=true) class meta: queryset = user.objects.all() resource_name = 'users' allowed_methods = ['get']
if you're after specific fields userprofile instance mixed in user, should able this:
class userresource(modelresource): date_of_birth = fields.datefield('profile__date_of_birth', null=true) class meta: queryset = user.objects.all() resource_name = 'users' allowed_methods = ['get'] fields = ['userfields', 'gohere', 'date_of_birth']
Comments
Post a Comment