0

我如何从另一个模型中引入信息?

我有两个模型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

4

1 回答 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分别表示如下:

  1. 表示集合的资源的项目相对导入路径

  2. 如果它在父模型上,则为字段的名称;如果在related_name 子模型上,则为字段的属性

  3. 是否将每个孩子的完整数据嵌入到提要中(True)或只是将资源链接嵌入到每个孩子(False)

于 2011-09-14T15:20:45.680 回答