I am trying to make an API using django RESTframework for a 5-star rating system. The API should render the list of all products in the home URL, and on each product, the average rating must be displayed. On clicking that, all the reviews for that particular product must be enlisted.
I have made my models, and views and the serializers.py file. The directory level is shown:
project_rating
├── reviews
│ ./apps.py
│ ./tests.py
│ ./views.py
│ ./admin.py
│ ./models.py
│ ./migrations
├── manage.py
├── api
│ ./apps.py
│ ./tests.py
│ ./urls.py
│ ./views.py
│ ./admin.py
│ ./models.py
│ ./migrations
│ ./serializers.py
My reviews/models.py looks like this:
class product(models.Model):
title = models.CharField(max_length = 100)
description = models.TextField()
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
review = models.ForeignKey('feedback', on_delete=models.CASCADE, null=True, default = "NA")
def __str__(self):
return self.title
class feedback(models.Model):
SCORE_CHOICES = zip(range(6), range(6) )
user = models.CharField(max_length=50, null= True, default='anonymous user')
item = models.ForeignKey(product, on_delete=models.SET_NULL, null= True)
rating = models.PositiveSmallIntegerField(choices=SCORE_CHOICES, blank=False)
def __str__(self):
return 'Rating(Item ='+ str(self.item)+', Stars ='+ str(self.rating)+')'
The api/serializers.py looks likes this:
class RatingSerializer(serializers.ModelSerializer):
class Meta:
model = models.feedback
fields=(
'id',
'user',
'rating',
)
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = models.product
fields=(
'id',
'title',
'description',
'review',
)
My api/views.py is:
class ProductList(generics.ListCreateAPIView):
queryset= models.product.objects.all()
serializer_class=serializers.ProductSerializer
class ReviewList(generics.ListCreateAPIView):
queryset=models.feedback.objects.all()
serializer_class= serializers.RatingSerializer
The api/urls.py is :
urlpatterns = [
path('',views.ProductList.as_view()),
path('<int:pk>/', views.ReviewList.as_view()),
]
The problem I am facing:
Q.I need to add a URL in the product_list(homepage) to link all the feedbacks for that product. How to add such URL and and make that URL display only those feedbacks which were made for that particular product?
I have tried to look for many available answers online, but couldn't solve my problem. If this question is redundant, kindly refer to the links which precisely solve my situation.
The github link to full code is : https://github.com/rjsu26/5-star-rating