如何从Django Tastypie中的相关模型返回数据?

时间:2011-09-14 10:52:33

标签: python django api django-models tastypie

如何从其他模型中引入信息?

我有两个模型ArticleArticleBody

包含主要信息的文章和包含正文和图像信息循环的ArticleBody

class Article(models.Model):
    author = models.ForeignKey(User)
    title = models.CharField(max_length=100)
    excerpt = models.CharField(max_length=140, null=True, blank=True, help_text='A description no longer than 140 characters that explains what the article is about, important for SEO')
    category = models.ManyToManyField(Category)
    date_published = models.DateTimeField()
    slug = models.SlugField(null=True)
    status = models.CharField(choices=STATUS, max_length=2, default='DR')
    tags = TagField(default='', null=True, blank=True, help_text='Just add a comma between the tags i.e. "My very important name, Hunting, Scope, Rifle"')
    source_name = models.CharField(default='', blank=True, null=True, help_text='Outdoor Magazine', max_length=100)
    source_url = models.URLField(verify_exists=False, max_length=200, null=True, blank=True, help_text='http://www.source.com/2011/01/long-name/')

class ArticleBody(ImageModel):
    article = models.ForeignKey(Article)
    body = models.TextField(verbose_name='', blank=True, null=True)
    image = models.ImageField(storage=cloudfiles_storage, upload_to='articles', default='avatar-blank.jpg', verbose_name='', blank=True, null=True)
    caption = models.CharField(max_length=80, null=True, blank=True)

在我的api resources.py文件中,我试图将ArticleBody信息放入我的NewsResource ......

这是我到目前为止所做的。

class NewsBodyResource(ModelResource):
    class Meta:
        queryset = ArticleBody.objects.all()
        resource_name = 'article_body'

class NewsResource(ModelResource):

    class Meta:
        queryset = Article.objects.filter(status='PU', date_published__lt=datetime.datetime.now).order_by('-date_published')
        resource_name = 'news'

正确的TastyPIE方式是什么,进行更改以便我可以将ArticleBody循环到我的NewsResource

1 个答案:

答案 0 :(得分:5)

class NewsBodyResource(ModelResource):
    class Meta:
        queryset = ArticleBody.objects.all()
        resource_name = 'article_body'

class NewsResource(ModelResource):
    newsbodies = fields.ToManyField('yourapp.api.resources.NewsBodyResource', 'articlebody_set', full=True)

    class Meta:
        queryset = Article.objects.filter(status='PU', date_published__lt=datetime.datetime.now).order_by('-date_published')
        resource_name = 'news'

ToManyField的参数分别代表以下内容:

  1. 表示集合

  2. 的资源的项目相对导入路径
  3. 字段名称,如果它在父模型或related_name上 该字段的属性(如果它在子模型上)

  4. 是否嵌入 每个孩子的完整数据到饲料(真实)或只是资源 每个孩子的链接(错误)