I have two models (customer, movie) and I would like to return (movie_name, customer_name, id) when I hit the URL (api/customer/1) and when I hit the URL (api/customer/1/movies) just wanted the movie names alone. How can we achieve this ?
models.py
class Customer(models.Model):
name = models.CharField(max_length=200, null=True)
class Movie(models.Model):
movie_name = models.CharField(max_length=200, null=True)
customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL)
serializers.py
class CustomerSerializer(serializers.ModelSerializer):
class Meta:
model = Customer
fields = ('id', 'name')
class MovieSerializer(serializers.ModelSerializer):
class Meta:
model = Movie
fields = '__all__'
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^api/customers/$', CustomerSerializer.as_view(), name='customers'),
]
Note:
- At the moment, when I hit the URL (api/customers) it returns the id, name of all the customers. Now, I would like to know, when I hit the URL (api/customer/1) how to list the same information along with movie names and when I hit the URL (api/customer/1/movies) how to just return the movie names alone?
