I cannot call the movies under a Director. I want to make a page where you click the name of the director and it will show the list of movies that are directed by the director. What shown below is the codes for models, serializers, and views.
models.py
class Director(models.Model):
_id = models.AutoField(primary_key=True)
firstname = models.CharField(max_length=100, null=True, blank=True)
lastname = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return "%s %s" % (self.firstname, self.lastname)
class Product(models.Model):
_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100, null=True, blank=True)
image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
description = models.TextField(null=True, blank=True)
director = models.ForeignKey(Director, on_delete=models.CASCADE)
def __str__(self):
return self.name
serializers.py
class ProductSerializer(serializers.ModelSerializer):
director = serializers.StringRelatedField()
class Meta:
model = Product
fields = '__all__'
class DirectorSerializer(serializers.ModelSerializer):
class Meta:
model = Director
fields = '__all__'
views.py
@api_view(['GET'])
def getProducts(request):
products = Product.objects.all()
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
@api_view(['GET'])
def getProduct(request, pk):
product = Product.objects.get(_id=pk)
serializer = ProductSerializer(product, many=False)
return Response(serializer.data)
@api_view(['GET'])
def getDirector(request):
director = Director.objects.all()
serializer = DirectorSerializer(director, many=True)
return Response(serializer.data)
I already tried what is shown above.
CodePudding user response:
views.py
@api_view(['GET'])
def getProductsByDirector(request, director_pk):
products = Product.objects.filter(director_id=director_pk)
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
Note: you don't need to add "_id" field in your models since it's automatically added.