0

I have models:

class Article(models.Model):
    name = models.CharField(max_length=255)
    symbol = models.CharField(max_length=255, unique=True)

    . . .

    def __unicode__(self):
        return '%s (%s)' % (self.name, self.symbol)


class ArticleRel(models.Model):
    active = models.BooleanField(default=True)
    create = models.DateTimeField(default=datetime.now)
    article = models.ForeignKey(Article)

    . . .

    def __unicode__(self):
        return '%s' % (self.id)

and resources:

class ArticleResource(ModelResource):
    owner = fields.ForeignKey(UserResource, 'owner')

    class Meta:
        queryset = Article.objects.all()
        resource_name = 'articles'
        serializer = Serializer()
        authorization = Authorization()
        filtering = {
            'owner': ALL_WITH_RELATIONS,
        }
        always_return_data = True

    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/(?P<id>\d+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
        ]


class ArticleRelResource(ModelResource):
    article = fields.ForeignKey(ArticleResource, 'article')

    class Meta:
        queryset = ArticleRel.objects.all()
        resource_name = 'article_rels'
        serializer = Serializer()
        authorization = Authorization()
        filtering = {
            'article': ALL_WITH_RELATIONS,
        }
        always_return_data = True

    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/(?P<id>\d+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
        ]

and now: how to set this resources so as to get articles with all article_rels in one query?

4

2 回答 2

0

这对我有用:

def dehydrate(self, bundle):
    bundle.data['rels'] = [ar.__dict__ for ar in ArticleRel.objects.filter(article__id=bundle.data['id'])]
    return bundle
于 2013-06-13T21:04:03.190 回答
0

我不确定我是否理解了这个问题。如果您的意思是要同时获取 article_rels 和文章,则可以在外键字段中使用 full=true。

article = fields.ForeignKey(ArticleResource, 'article', full=True)

如文档中所述 - http://django-tastypie.readthedocs.org/en/latest/fields.html#full

请记住额外数据库查询的开销时间。

于 2013-06-13T04:13:35.013 回答