如何获得相关资源?

时间:2013-06-11 20:57:34

标签: tastypie

我有模特:

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)

和资源:

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

现在:如何设置这些资源,以便在一个查询中获取包含所有article_rels的文章?

2 个答案:

答案 0 :(得分:0)

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

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

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

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

答案 1 :(得分:0)

这项工作对我来说:

def dehydrate(self, bundle):
    bundle.data['rels'] = [ar.__dict__ for ar in ArticleRel.objects.filter(article__id=bundle.data['id'])]
    return bundle