我有两个表(电影和流派),它们使用交叉表(电影流派)以多对多关系连接。
我的 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 )
我想用美味派过滤某些类型的所有电影。例如,向我展示所有类型为动作、惊悚和科幻的电影。
我的 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,
}
我的测试数据:两部电影(带有流派 id)矩阵(1 和 3)银翼杀手(1 和 2)
首先我对标题进行查询,如下查询返回1个结果(即矩阵):
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
任何想法使这项工作?
感谢您的任何想法...