python - Tastypie serializing Virtual Field's Model -
python - Tastypie serializing Virtual Field's Model -
i've patient, doctor, story model. each story have patient_id , doctor_id. want retrieve list of doctors patient have visited ever.
class patient(person): def visits(self): doctor_visits = [] v in self.stories.values('doctor').annotate(visits=count('doctor')): # replace doc id doc object v['doctor'] = doctor.objects.get(id=v['doctor']) doctor_visits.append(v) homecoming doctor_visits here tastypie resource
class patientresource(modelresource): stories = fields.tomanyfield('patients.api.storyresource', 'stories', null=true) visits = fields.listfield(attribute='visits', readonly=true) class meta: queryset = patient.objects.all() excludes = ['id', 'login', 'password'] with above tastypie results following
{ address:"address", dob:"1985-12-04", email:"email", name:"nogen", resource_uri:"/patients/api/v1/patient/9/", sex:"m", stories:[ "/patients/api/v1/story/1/", "/patients/api/v1/story/2/", "/patients/api/v1/story/4/" ], visits:[ { doctor:"dr. x", visits:2 }, { doctor:"dr. y", visits:1 } ] } see caling __unicode__ method of doctor rather expected link /patients/api/v1/doctor/<doctor_id>/ need build path manually or there other way around ?
i've tried using dehydrate perchance incorrectly
class patientresource(modelresource): stories = fields.tomanyfield('patients.api.storyresource', 'stories', null=true) visits = fields.listfield(attribute='visits', readonly=true) class meta: queryset = patient.objects.all() excludes = ['id', 'login', 'password'] def dehydrate_visits(self, bundle): visit in bundle.data['visits']: visit['doctor'] = doctorresource(visit['doctor']) homecoming bundle which results in maximum recursion depth exceeded while calling python object exception
not sure why maximum recursion depth method wrong.
class patientresource(modelresource): [...] def dehydrate_visits(self, bundle): # create sure `bundle.data['visits'][0]['doctor'] isn't string. # if it's dehydrated string: seek utilize `bundle.obj.visits` instead. visit in bundle.data['visits']: visit['doctor'] = doctorresource.get_resource_uri(visit['doctor']) homecoming bundle i didn't test that. fill free comment if incorrect.
python django rest tastypie
Comments
Post a Comment