Feedback Tastypie

I am trying to get the api to give me feedback data with tastypie.

I have two models: DocumentContainer and DocumentEvent, they are related as:

There are many DocumentEvents in the DocumentContainer

Here is my code:

class DocumentContainerResource(ModelResource): pod_events = fields.ToManyField('portal.api.resources.DocumentEventResource', 'pod_events') class Meta: queryset = DocumentContainer.objects.all() resource_name = 'pod' authorization = Authorization() allowed_methods = ['get'] def dehydrate_doc(self, bundle): return bundle.data['doc'] or '' class DocumentEventResource(ModelResource): pod = fields.ForeignKey(DocumentContainerResource, 'pod') class Meta: queryset = DocumentEvent.objects.all() resource_name = 'pod_event' allowed_methods = ['get'] 

When I hit my api url, I get the following error:

 DocumentContainer' object has no attribute 'pod_events 

Can anyone help?

Thanks.

+7
source share
2 answers

I made a blog entry about this here: http://djangoandlove.blogspot.com/2012/11/tastypie-following-reverse-relationship.html .

Here is the basic formula:

API.py

 class [top]Resource(ModelResource): [bottom]s = fields.ToManyField([bottom]Resource, '[bottom]s', full=True, null=True) class Meta: queryset = [top].objects.all() class [bottom]Resource(ModelResource): class Meta: queryset = [bottom].objects.all() 

Models.py

 class [top](models.Model): pass class [bottom](models.Model): [top] = models.ForeignKey([top],related_name="[bottom]s") 

This requires

  • a models.ForeignKey relationship from child to parent in this case
  • using linked_name
  • defining a top resource to use the associated_name as an attribute.
+12
source

Change your line in class DocumentContainerResource(...) , from

 pod_events = fields.ToManyField('portal.api.resources.DocumentEventResource', 'pod_events') 

to

 pod_events = fields.ToManyField('portal.api.resources.DocumentEventResource', 'pod_event_set') 

The suffix for pod_event in this case should be _set , but depending on the situation, the suffix can be one of the following:

  • _set
  • _s
  • (no suffix)

If each event can be associated with only one container, also consider changing:

 pod = fields.ForeignKey(DocumentContainerResource, 'pod') 

in

 pod = fields.ToOneField(DocumentContainerResource, 'pod') 
+1
source

All Articles