I'm working on a django based restaurant review site. When user sends reviews they fill in a form which consists of two choice fields. Currently I can display all reviews for a specific restaurant in a Detailview page. I would like to take the information from the choice fields from the comment form to display this data for the user in both the detail view (1 specific restaurant) as well as the list view (all restaurant listed):
Question:
- I would like to get the total number of "votes" for each choice and display it with for example Chart Js in the detail view. What is the prefered way or doing so in django? I have tried to do this filtering in javascript, however I know that this could be done more efficiently directly in the model or in the view.
Code
Models.py
class Restaurant(models.Model):
name = models.CharField(max_length = 100)
class Comment(models.Model):
STATUS_1 = (
('one', 'one'),
('two', 'two'),
('three', 'three'),
)
STATUS_2 = (
('cheap', 'cheap'),
('normal', 'normal'),
('expensive', 'expensive'),
)
restaurant = models.ForeignKey(Restaurant, on_delete = models.CASCADE, related_name='comments')
comment = models.TextField(max_length = 500)
status_1 = models.CharField(max_length = 100, choices=STATUS_1)
status_2 = models.CharField(max_length = 100, choices=STATUS_2)
views.py
class RestaurantDetailView(DetailView):
model = Restaurant
form_class = CommentForm
template_name = 'core/restaurant_detail.html'
def get_context_data(self, **kwargs):
context = super(RestaurantDetailView, self).get_context_data(**kwargs)
comment_form = CommentForm
context['comment_form'] = comment_form
return context
def point_dataset(self, request):
points = serialize('geojson', Restaurant.objects.all())
return HttpResponse(points, content_type='json')
def get_queryset(self):
return Restaurant.objects.annotate(avg_rating=Avg('comments__rate'))
For example:
If a specific restaurant has 3 reviews with results: STATUS_1 = 'one', 'one', 'two' and STATUS_2 = 'normal', 'cheap', 'normal', how do I get the following data passed to chart js:
STATUS_1: ['one': '2', 'two': '1', 'three': '0']
STATUS_2: ['cheap': '1', 'normal': '2', 'expensive': '0']