Browse Source

Add API support for restaurant,food and drink views, restaurant rating

master
Apostolos Fanakis 6 years ago
parent
commit
ee8e1f76b6
  1. 25
      UI/Database API/hyrieus/flavoursAPI/hyrieus/migrations/0002_auto_20190110_2042.py
  2. 4
      UI/Database API/hyrieus/flavoursAPI/hyrieus/models.py
  3. 15
      UI/Database API/hyrieus/flavoursAPI/hyrieus/urls.py
  4. 147
      UI/Database API/hyrieus/flavoursAPI/hyrieus/views.py

25
UI/Database API/hyrieus/flavoursAPI/hyrieus/migrations/0002_auto_20190110_2042.py

@ -0,0 +1,25 @@
# Generated by Django 2.1.4 on 2019-01-10 20:42
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('hyrieus', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='userratesrestaurant',
name='rating_date',
field=models.DateField(auto_now=True),
),
migrations.AlterField(
model_name='userratesrestaurant',
name='user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL),
),
]

4
UI/Database API/hyrieus/flavoursAPI/hyrieus/models.py

@ -175,11 +175,11 @@ class UserRatesFood(models.Model):
class UserRatesRestaurant(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, models.DO_NOTHING)
user = models.ForeignKey(settings.AUTH_USER_MODEL, models.DO_NOTHING, blank=True, null=True)
restaurant = models.ForeignKey(Restaurant, models.DO_NOTHING)
diet = models.ForeignKey(Diet, models.DO_NOTHING, blank=True, null=True)
rating_grade = models.IntegerField()
rating_date = models.DateField()
rating_date = models.DateField(auto_now=True)
rating_text = models.CharField(max_length=700, blank=True, null=True)
rating_accessibility = models.CharField(max_length=8, blank=True, null=True)

15
UI/Database API/hyrieus/flavoursAPI/hyrieus/urls.py

@ -2,11 +2,12 @@ from django.conf.urls import url
from django.urls import include, path
from rest_framework import routers
from flavoursAPI.hyrieus.views import (DietViewSet, DietProhibitsIngredientViewSet,
DrinkViewSet, DrinkHasIngredientViewSet, FoodViewSet, FoodHasIngredientViewSet,
IngredientViewSet, PermissionViewSet, RestaurantViewSet, RoleViewSet,
RoleHasPermissionViewSet, UserViewSet, UserFollowsDietViewSet,
UserProhibitsIngredientViewSet, UserRatesDrinkViewSet, UserRatesFoodViewSet,
UserRatesRestaurantViewSet, UserSetBirthDay,
DrinkViewSet, DrinkHasIngredientViewSet, FoodViewSet, FoodHasIngredientViewSet,
IngredientViewSet, PermissionViewSet, RestaurantViewSet, RoleViewSet,
RoleHasPermissionViewSet, UserViewSet, UserFollowsDietViewSet,
UserProhibitsIngredientViewSet, UserRatesDrinkViewSet, UserRatesFoodViewSet,
UserRatesRestaurantViewSet, UserSetBirthDay, RestaurantUserView, UserDiets,
FoodUserView, DrinkUserView,
)
router = routers.DefaultRouter()
@ -31,6 +32,10 @@ router.register(r'userratesrestaurant', UserRatesRestaurantViewSet)
urlpatterns = [
# url(r'signup', Signup.as_view()),
path('setUserBirthday/<int:pk>/', UserSetBirthDay.as_view(), name='setUserBirthday'),
path('restaurantUserView/<int:restaurant>/', RestaurantUserView.as_view(), name='restaurantUserView'),
path('foodUserView/<int:food>/', FoodUserView.as_view(), name='foodUserView'),
path('drinkUserView/<int:drink>/', DrinkUserView.as_view(), name='drinkUserView'),
path('userDiets/', UserDiets.as_view(), name='userDiets'),
path('rest-auth/', include('rest_auth.urls')),
url(r'^rest-auth/registration/', include('rest_auth.registration.urls'))
]

147
UI/Database API/hyrieus/flavoursAPI/hyrieus/views.py

@ -1,6 +1,7 @@
from django.shortcuts import render
from django.http import Http404
from decimal import Decimal
from django.db.models import F, ExpressionWrapper, FloatField
from django.db.models import F, ExpressionWrapper, FloatField, Avg, Prefetch
from rest_framework.views import APIView
from rest_framework import viewsets
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
@ -297,6 +298,19 @@ class UserRatesRestaurantViewSet(viewsets.ModelViewSet):
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
def perform_create(self, serializer):
user = self.request.user
try:
restaurant = Restaurant.objects.get(pk=self.request._data.get('restaurant'))
except Restaurant.DoesNotExist:
raise Http404
if restaurant.restaurant_is_approved == 0:
raise PermissionDenied({"message":"You don't have permission to access"})
serializer.save(user=user)
def get(self, request, format=None):
content = {
'user': unicode(request.user),
@ -314,7 +328,7 @@ class UserSetBirthDay(APIView):
def put(self, request, pk, format=None):
try:
user = User.objects.get(pk=pk)
except Snippet.DoesNotExist:
except User.DoesNotExist:
raise Http404
if not request.user == user:
@ -325,3 +339,132 @@ class UserSetBirthDay(APIView):
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class RestaurantUserView(APIView):
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
def get(self, request, restaurant, format=None):
try:
restaurant = Restaurant.objects.get(restaurant_id=restaurant)
except Restaurant.DoesNotExist:
raise Http404
user = request.user
if (not user.role.role_id == 1) and (restaurant.restaurant_is_approved == 0):
raise PermissionDenied({"message":"You don't have permission to access"})
userDiets = UserFollowsDiet.objects.all().filter(user=user).only('diet')
restaurantRatings = UserRatesRestaurant.objects.filter(restaurant=restaurant) \
.prefetch_related('user')
averageRating = restaurantRatings.aggregate(Avg('rating_grade'))
ratingsPerDiet = restaurantRatings.prefetch_related('diet') \
.values('diet').filter(diet__in=[ud.diet for ud in userDiets]) \
.annotate(average_rating = Avg('rating_grade')) \
.annotate(diet_name = F('diet__diet_name'))
restaurantRatings = restaurantRatings.annotate(username = F('user__username')).values()
restaurantFoods = Food.objects.all().filter(restaurant=restaurant)
restaurantDrinks = Drink.objects.all().filter(restaurant=restaurant)
foods = [FoodSerializer(food).data for food in list(restaurantFoods)]
drinks = [DrinkSerializer(drink).data for drink in list(restaurantDrinks)]
data = {'restaurantInfo': RestaurantSerializer(restaurant).data,
'averageRating': averageRating,
'avgRatingPerDiet': ratingsPerDiet,
'foods': foods,
'drinks': drinks,
'ratings': restaurantRatings}
return Response(data)
class UserDiets(APIView):
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
def get(self, request, format=None):
user = request.user
userDiets = UserFollowsDiet.objects.all().filter(user=user).prefetch_related('diet')
userDiets = Diet.objects.filter(diet_id__in = userDiets.values('diet')) \
.values('diet_id', 'diet_name')
return Response(userDiets)
class FoodUserView(APIView):
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
def get(self, request, food, format=None):
try:
food = Food.objects.get(food_id=food)
except Food.DoesNotExist:
raise Http404
user = request.user
if (not user.role.role_id == 1) and (food.food_is_approved == 0):
raise PermissionDenied({"message":"You don't have permission to access"})
servingRestaurant = food.restaurant.restaurant_name
foodRatings = UserRatesFood.objects.filter(food=food).prefetch_related('user')
averageRating = foodRatings.aggregate(Avg('rating_grade'))
foodRatings = foodRatings.annotate(username = F('user__username')).values()
foodIngredients = FoodHasIngredient.objects.filter(food=food).prefetch_related('ingredient_name')
foodIngredients = Ingredient.objects.filter(ingredient_name__in = foodIngredients.values('ingredient_name'))
foodIngredients = [IngredientSerializer(ingredient).data for ingredient in list(foodIngredients)]
data = {'foodInfo': FoodSerializer(food).data,
'restaurantName': servingRestaurant,
'averageRating': averageRating,
'ingredients': foodIngredients,
'ratings': foodRatings}
return Response(data)
class DrinkUserView(APIView):
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
def get(self, request, drink, format=None):
try:
drink = Drink.objects.get(drink_id=drink)
except Drink.DoesNotExist:
raise Http404
user = request.user
if (not user.role.role_id == 1) and (drink.drink_is_approved == 0):
raise PermissionDenied({"message":"You don't have permission to access"})
servingRestaurant = drink.restaurant.restaurant_name
drinkRatings = UserRatesDrink.objects.filter(drink=drink).prefetch_related('user')
averageRating = drinkRatings.aggregate(Avg('rating_grade'))
drinkRatings = drinkRatings.annotate(username = F('user__username')).values()
drinkIngredients = DrinkHasIngredient.objects.filter(drink=drink).prefetch_related('ingredient_name')
drinkIngredients = Ingredient.objects.filter(ingredient_name__in = drinkIngredients.values('ingredient_name'))
drinkHasAlcohol = drinkIngredients.filter(ingredient_has_alcohol=True).count()
drinkIngredients = [IngredientSerializer(ingredient).data for ingredient in list(drinkIngredients)]
data = {'drinkInfo': DrinkSerializer(drink).data,
'restaurantName': servingRestaurant,
'averageRating': averageRating,
'drinkHasAlcohol': True if drinkHasAlcohol>0 else False,
'ingredients': drinkIngredients,
'ratings': drinkRatings}
return Response(data)
Loading…
Cancel
Save