【问题标题】:How do I return data from a related model in Django Tastypie?如何从 Django Tastypie 中的相关模型返回数据?
【发布时间】:2011-09-14 10:52:33
【问题描述】:

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

我有两个型号ArticleArticleBody

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

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 中?

【问题讨论】:

    标签: python django api django-models tastypie


    【解决方案1】:
    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. 是否嵌入 每个孩子的完整数据进入提要(真)或只是资源 指向每个孩子的链接(错误)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-25
      • 2012-06-22
      • 1970-01-01
      • 2010-10-02
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多