From 87ca86bf61d6c8fd211aaa501bdf886e04c1ca36 Mon Sep 17 00:00:00 2001 From: Samuel Huang Date: Sat, 11 Jul 2020 22:28:03 -0700 Subject: [PATCH] Enable custom queries in RestaurantListView --- places/migrations/0010_auto_20200712_0505.py | 16 +++++++++++ places/models.py | 1 + places/views.py | 28 +++++++++++++++++++- 3 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 places/migrations/0010_auto_20200712_0505.py diff --git a/places/migrations/0010_auto_20200712_0505.py b/places/migrations/0010_auto_20200712_0505.py new file mode 100644 index 0000000..986953e --- /dev/null +++ b/places/migrations/0010_auto_20200712_0505.py @@ -0,0 +1,16 @@ +# Generated by Django 3.0.8 on 2020-07-12 05:05 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ("places", "0009_auto_20200712_0155"), + ] + + operations = [ + migrations.AlterModelOptions( + name="restaurant", options={"ordering": ["name"]}, + ), + ] diff --git a/places/models.py b/places/models.py index b28f997..46b0396 100644 --- a/places/models.py +++ b/places/models.py @@ -17,6 +17,7 @@ class Restaurant(models.Model): class Meta: db_table = "restaurant" + ordering = ["name"] def average_rating(self): ratings_count = 0 diff --git a/places/views.py b/places/views.py index a1044c4..55497df 100644 --- a/places/views.py +++ b/places/views.py @@ -1,4 +1,5 @@ from django.contrib.auth.mixins import LoginRequiredMixin +from django.db.models import Q from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse @@ -17,10 +18,35 @@ class HomeView(TemplateView): class RestaurantListView(ListView): model = Restaurant - ordering = ["name"] paginate_by = 15 context_object_name = "restaurant_list" + @staticmethod + def get_composite_key(queries): + composite = queries[0] + for query in queries[1:]: + composite &= query + return composite + + def get_queryset(self): + queries = [] + name = self.request.GET.get("name") + if name: + queries.append(Q(name__contains=name)) + category = self.request.GET.get("category") + if category: + queries.append(Q(categories__name__contains=category)) + min_party = self.request.GET.get("min_party") + if min_party and min_party.isdigit(): + queries.append(Q(min_party__gte=min_party)) + max_party = self.request.GET.get("max_party") + if max_party and max_party.isdigit(): + queries.append(Q(max_party__lte=max_party)) + if queries: + composite = self.get_composite_key(queries) + return Restaurant.objects.filter(composite) + return Restaurant.objects.all() + class RestaurantDetailView(DetailView): model = Restaurant