Search code examples
djangotastypie

How to do a Left Join query with Where clause in TastyPie?


I am using TastyPie and trying to figure out how to retrieve all Articles that have a Section either with title 'Section X' or 'Section Y'.

In SQL it would be something like:

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

Here is the TastyPie code I have so far:

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']

This seems like it should be a simple thing, but I don't seem to be able to find any documentation or examples that I can make work.

Adding relevant Django model information as requested:

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

Any ideas?


Solution

  • In querystring:

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

    Somwhere in ArticleResource:

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