tastypie:使用多个ANDed值过滤多个到多个表

时间:2013-02-28 15:41:23

标签: django filter tastypie relation m2m

我有两个表(电影和流派)使用crosstable(MovieGenre)与多对多关系连接。

我的models.py文件如下所示:

class Genre( models.Model ):

    sName = models.CharField( max_length=176)
    [ .. ]

class Movie( models.Model ):

    sTitle = models.CharField( max_length=176)
    genre = models.ManyToManyField( Genre )
    [ .. ]

class MovieGenre( models.Model ):

    idMovie = models.ForeignKey( Movie )
    idGenre = models.ForeignKey( Genre )

我想用tastypie来过滤某些类型的电影。例如。给我看所有类型动作,惊悚和科幻的电影。

我的api.py看起来像这样:

class GenreResource(ModelResource):
    class Meta:
        queryset = Genre.objects.all()
        resource_name = 'genre'
        always_return_data = True
        include_resource_uri = False
        excludes = ['dtCreated', 'dtModified' ]
        authorization= Authorization()
        authentication = SessionAuthentication()
        filtering = {
            "id" : ALL,
        }


class MovieResource(ModelResource):
    genre = fields.ManyToManyField( 'app.api.GenreResource', 'genre', full=True )
    class Meta:
        queryset = Movie.objects.all()
        resource_name = 'movie'
        authorization= Authorization()
        authentication = SessionAuthentication()
        always_return_data = True
        include_resource_uri = False
        excludes = ['dtCreated', 'dtModified' ]
        filtering = {
            "sTitle" : ALL,
            "genre" : ALL_WITH_RELATIONS,
        }

我的测试数据: 两部电影(带流派ids) 矩阵(1& 3) Blade Runner(1& 2)

首先我对标题进行查询,正如下面预期的那样,查询返回1个结果(即Matrix):

   http://localhost:8000/api/v1/movie/?format=json&sTitle__icontains=a&sTitle__icontains=x

但是,我得到三个结果,其URL应该使用此查询查询相关的类型表(两次Matrix和一次Blade Runner):

    http://localhost:8000/api/v1/movie/?format=json&genre__id__in=3&genre__id__in=1

我希望只回到Matrix

我也试图像这样覆盖apply_filters:

def apply_filters(self, request, applicable_filters):
    oList = super(ModelResource, self).apply_filters(request, applicable_filters)
    loQ = [Q(**{'sTitle__icontains': 'a'}), Q(**{'sTitle__icontains': 'x'})]
    # works as intended: one result
    loQ = [Q(**{'genre__id__in': '3'}) ]
    # results in one result (Matrix)

    loQ = [Q(**{'genre__id__in': '1'}), Q(**{'genre__id__in': '3'}) ]
    # results in no results!

    loQ = [Q(**{'genre__id__in': [ 1, 3]}) ]
    # results in two results Matrix and Blade Runner which is OK since obviously ORed
    oFilter = reduce( operator.and_, loQ )
    oList = oList.filter( oFilter ).distinct()
    return oList

任何想法让这项工作?

感谢您的任何想法...

1 个答案:

答案 0 :(得分:3)

您是否尝试过http://localhost:8000/api/v1/movie/?format=json&genre__id=3&genre__id=1

如果我理解正确,那么使用__in就像说genre__id__in=[1, 3]