2013-06-11 76 views
0

我有型號:如何獲取相關資源?

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得到物品?

回答

0

我不確定我是否理解了這個問題。 如果您的意思是您希望獲得article_rels和articles,則可以在外鍵字段中使用full = true。

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

如文檔中表示 - http://django-tastypie.readthedocs.org/en/latest/fields.html#full

請的額外的數據庫查詢的開銷時頭腦。

0

這項工作對我來說:

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