2012-11-19 10 views
7

私は私のapiが私にtastypieと逆の関係データを与えるようにしようとしています。Tastypie Reverse Relation

私は2つのモデル、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
_setにする必要がありますが、状況に応じて、サフィックスがのいずれかの可能性があり、この場合に pod_eventため

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

から

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

サフィックスに、class DocumentContainerResource(...)であなたの行を変更し

以下:

  • _set
  • _s
  • (接尾辞なし)

各イベントはまた、変更することを検討し、1つまでのコンテナに関連付けることができます場合は、次へ

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を使用すると、related_nameを属性として使用する最上位リソース定義が返されます。
+0

ありがとう、これは私を助けてくれました。 ToManyFieldのrelated_name = '[top]'属性がありません。これにより、作成時にデータが入力されます。参照:http://django-tastypie.readthedocs.org/en/latest/fields.html#tastypie.fields.RelatedField.related_name –