when user goes to http://127.0.0.1:8000/movies/
, I don't want to show the Showtimes
but when user goes to http://127.0.0.1:8000/movies/1/
, show it .
I want to ask if there is method to do this??
The method I use now is write 2 ModelSerializer to display it.
Please guide me . Thank you!!
This is my original code (not the 2 ModelSerializer method)
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'),
This is my views.py :
class MovieMixin(object):
queryset = Movie.objects.all()
serializer_class = MovieSerializer
class MovieFilter(django_filters.FilterSet):
class Meta:
model = Movie
fields = ['which_run',]
class MovieList(MovieMixin, generics.ListAPIView):
filter_class = MovieFilter
class MovieDetail(MovieMixin, generics.RetrieveAPIView):
pass
This is my serializes.py
class MovieSerializer(serializers.ModelSerializer):
class Meta:
model = Movie
fields = ('id', 'title','Showtimes',)
You can do this with two serializers, by swapping out the serializer in the get_serializer_class
method on the serializer. This will work with all generic views, including ViewSet
instances. In your case, you can also just override serializer_class
on the detail view with the custom serializer.
class MovieMixin(object):
queryset = Movie.objects.all()
class MovieList(MovieMixin, generics.ListAPIView):
filter_class = MovieFilter
serializer_class = MovieSerializer
class MovieDetail(MovieMixin, generics.RetrieveAPIView):
serializer_class = MovieDetailSerializer
There are also plugins that allow you to do this, the most notable being the one included with drf-extensions
.
These will both require a new serializer that will handle just the detail view representation.
class MovieSerializer(serializers.ModelSerializer):
class Meta:
model = Movie
fields = ('id', 'title', )
class MovieDetailSerializer(MovieSerializer):
class Meta(MovieSerializer.Meta:
fields = MovieSerializer.Meta.fields + ('Showtimes', )
This will allow you to have two different serialized responses for the list view and the detail view.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.