Have you tried http://localhost:8000/api/v1/movie/?format=json&genre__id=3&genre__id=1
If I understand correctly, using __in
that way would be like saying genre__id__in=[1, 3]
.
문제
I have two tables (Movie and Genre) that are connected with a many to many relation using a crosstable (MovieGenre).
My models.py file looks like this:
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 )
I want to use tastypie to filter all movies of certain genres. E.g. show me all movies that are of genre Action, Thriller and SciFi.
My api.py looks like this:
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,
}
My test data: Two movies (with genre ids) Matrix (1 & 3 ) Blade Runner (1 & 2 )
First I make a query on the title, as expected below query returns 1 result (namely Matrix):
http://localhost:8000/api/v1/movie/?format=json&sTitle__icontains=a&sTitle__icontains=x
However, I get three results with the URL that should query the related genre table (two times Matrix and once Blade Runner) with this query:
http://localhost:8000/api/v1/movie/?format=json&genre__id__in=3&genre__id__in=1
I would expect to get back only Matrix
I also tried to override apply_filters like so:
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
Any idea to make this work?
Thanks for any idea...
해결책
Have you tried http://localhost:8000/api/v1/movie/?format=json&genre__id=3&genre__id=1
If I understand correctly, using __in
that way would be like saying genre__id__in=[1, 3]
.