如何在TastyPie中使用Where子句进行左连接查询?

时间:2016-08-20 03:30:23

标签: django tastypie

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

在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

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

在查询字符串中:

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

ArticleResource中的某个地方:

self.queryset.filter(section__title__in=['Section X', 'Section Y'])
相关问题