【问题标题】:How to do a Left Join query with Where clause in TastyPie?如何在 TastyPie 中使用 Where 子句进行左连接查询?
【发布时间】:2016-08-20 03:30:22
【问题描述】:

我正在使用 TastyPie 并试图弄清楚如何检索所有标题为“Section X”或“Section Y”的文章。

在 SQL 中会是这样的:

SELECT * FROM Article a, Section s 
WHERE a.section_id = s.id 
AND s.title IN ('Section X', 'Section Y')

这是我目前拥有的 TastyPie 代码:

class ArticleResource(ModelResource):
    section = fields.ToOneField('myapp.api.SectionResource', 'section')

    class Meta:
        queryset = Article.objects.all()
        resource_name = 'articles'
        fields = ['id','section','text',]
        filtering = {
            'section': ALL_WITH_RELATIONS,
        }
        allowed_methods = ['get']

class SectionResource(ModelResource):
    class Meta:
        queryset = Section.objects.all()
        resource_name = 'sections'
        fields = ['title',]
        filtering = { "title" : ALL }
        allowed_methods = ['get']

这似乎应该是一件简单的事情,但我似乎无法找到任何我可以使用的文档或示例。

按要求添加相关的Django模型信息:

class Article(models.Model):
    title = models.CharField(max_length=200)
    text = models.TextField(max_length=2000,null=True)
    section = models.ForeignKey(Section,null=True)

    def __unicode__(self): #Python 3: def __str__(self):
        return self.title

class Section(models.Model):
    title = models.CharField(max_length=200)

    def __unicode__(self): #Python 3: def __str__(self):
        return self.title

有什么想法吗?

【问题讨论】:

  • 显示你的 Django 模型定义
  • @TomaszJakubRup -- 我刚刚在原始描述中添加了 django 模型。

标签: django tastypie


【解决方案1】:

在查询字符串中:

/api/v1/articles/?section__title__in=Section X,Section Y

ArticleResource 某处:

self.queryset.filter(section__title__in=['Section X', 'Section Y'])

【讨论】:

  • @TomaszJakubRub -- 谢谢!这成功了,现在我更好地理解了如何过滤连接表值的资源。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-01
  • 1970-01-01
  • 2017-07-04
  • 2018-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多