我对过滤查询参数有疑问。
这是我的代码:
models.py
class Movie(models.Model):
link = models.URLField()
title = models.CharField(max_length=255, null=True)
class MovieTheater(models.Model):
movietheater = models.ManyToManyField(Movie,null=True,blank=True,through="MovieShowtime")
movie_theater = models.CharField(max_length=255, null=True)
city = models.CharField(max_length=255, null=True) #east west north south
class MovieShowtime(models.Model):
theater = models.ForeignKey( MovieTheater, null=True,blank=True,related_name = 'theater' )
movie = models.ForeignKey( Movie, null=True,blank=True,related_name = 'movie' )
time = models.TextField(null=True,blank=True)
serialize.py
class MovieShowtimeSerializer(serializers.ModelSerializer):
movietitle = serializers.CharField(source='movie.title')
theatertitle = serializers.CharField(source='theater.movie_theater')
area = serializers.CharField(source='theater.city')
class Meta:
model = MovieShowtime
fields = ( 'movietitle', 'theatertitle','time','area')
class MovieSerializer(serializers.ModelSerializer):
movielink = serializers.HyperlinkedIdentityField(view_name='movie-detail')
showtime = MovieShowtimeSerializer(many=True, read_only=True, source='movie')
class Meta:
model = Movie
fields = ('movielink' ,'title','showtime' )
urls.py:
urlpatterns = patterns('',
url(r'^movies/$', MovieList.as_view(), name='movie-list'),
url(r'^movies/(?P<pk>[0-9]+)$', MovieDetail.as_view(), name='movie-detail'),)
我想设计一个类似http://127.0.0.1:8000/movies/88?city=XXX
当区域等于“北方”时,它将匹配结果。 &#39;东&#39;&#39;南&#39;&#39;西&#39;
我必须连接两个模型,如:
queryset = Movie.objects.filter(pk=88)
queryset2 = queryset.movietheater_set.filter(city='north')
但我不知道如何在我的views.py
中做到这一点请教我 - 谢谢。
答案 0 :(得分:0)
你想要的是FilterSet。在您的情况下,将它添加到视图中可能就足够了:
class MovieList(MovieMixin, generics.ListAPIView):
filter_fields = ('showtime__theater__area',)
您的模型还需要一些工作。相关名称允许您从外键访问。目前你可以获得Movie.movie,当你可能想要Movie.showtime
时class MovieShowtime(models.Model):
theater = models.ForeignKey( MovieTheater, null=True,blank=True,related_name = 'theater' )
movie = models.ForeignKey( Movie, null=True,blank=True,related_name = 'showtime' )
time = models.TextField(null=True,blank=True)
序列化需要一些调整:
class MovieShowtimeSerializer(serializers.ModelSerializer):
movietitle = serializers.CharField(source='movie.title')
theatertitle = serializers.CharField(source='theater.movie_theater')
class MovieSerializer(serializers.ModelSerializer):
movielink = serializers.HyperlinkedIdentityField(view_name='movie-detail')
showtime = MovieShowtimeSerializer(many=True, read_only=True, source='movie')
您可以制作自定义过滤器以缩短filter_fields url参数。