2012-11-19 135 views
7

我想讓我的api給我與tastypie的反向關係數據。Tastypie反向關係

我有兩個型號,DocumentContainer和的DocumentEvent,它們是相關的:

DocumentContainer有許多DocumentEvents

這裏是我的代碼:

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'] 

當我打我的API URL,我得到以下錯誤:

DocumentContainer' object has no attribute 'pod_events 

任何人都可以幫忙嗎?

謝謝。

回答

1

更改線class DocumentContainerResource(...),從

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

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

在這種情況下pod_event的後綴應該是_set,但根據情況,後綴可以是一個以下:

  • _set
  • _s
  • (無後綴)

如果每個事件只能與最多一個容器相關聯,也考慮改變:

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

到:

pod = fields.ToOneField(DocumentContainerResource, 'pod') 
+0

嗯,即使在更改後,它不適用於我。現在它說「'DocumentContainer'對象沒有屬性'pod_event_set'」 – rookieRailer

+0

@rookieRailer你會介意從你的models.py中發佈相關的片段嗎? –

+1

ForeignKey是ToOneField的別名。 –

12

我在這裏寫了一篇博客文章:http://djangoandlove.blogspot.com/2012/11/tastypie-following-reverse-relationship.html

下面是基本公式:

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") 

它需要

  1. 從孩子一models.ForeignKey關係在這種情況下給父母
  2. 使用related_name
  3. 頂部資源定義使用related_name作爲屬性。
+0

謝謝,這對我幫助很大。 雖然我錯過了ToManyField中的related_name ='[top]'屬性。這確保數據在創建時被填充。請參閱:http://django-tastypie.readthedocs.org/en/latest/fields.html#tastypie.fields.RelatedField.related_name –