7

私は API を取得して、tastypie との逆の関係データを取得しようとしています。

DocumentContainer と DocumentEvent の 2 つのモデルがあり、次のように関連しています。

DocumentContainer には多くの DocumentEvent があります

これが私のコードです:

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

誰でも助けることができますか?

ありがとう。

4

2 に答える 2

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

モデル.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 を属性として使用する最上位のリソース定義。
于 2012-11-20T22:50:51.030 に答える
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
  • (サフィックスなし)

各イベントを最大 1 つのコンテナーにしか関連付けることができない場合は、次の変更も検討してください。

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

に:

pod = fields.ToOneField(DocumentContainerResource, 'pod')
于 2012-11-20T00:43:06.977 に答える