如何在Django Tastypie中返回相关模型的数据?
我该如何把另一个模型的信息引入进来呢?
我有两个模型,分别是 Article
和 ArticleBody
。
Article
里包含主要信息,而 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 个回答
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
的参数分别代表以下内容:
资源的导入路径,这个路径是相对于项目的,用来表示一组数据
如果这个字段在父模型上,就写字段的名字;如果在子模型上,就写这个字段的
related_name
属性是否要把每个子项的完整数据嵌入到信息中(选择True),还是只放每个子项的链接(选择False)