Skip to content

Commit

Permalink
Enable custom queries in RestaurantListView
Browse files Browse the repository at this point in the history
  • Loading branch information
huangsam committed Jul 12, 2020
1 parent 752fbdc commit 87ca86b
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 1 deletion.
16 changes: 16 additions & 0 deletions places/migrations/0010_auto_20200712_0505.py
Original file line number Diff line number Diff line change
@@ -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"]},
),
]
1 change: 1 addition & 0 deletions places/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class Restaurant(models.Model):

class Meta:
db_table = "restaurant"
ordering = ["name"]

def average_rating(self):
ratings_count = 0
Expand Down
28 changes: 27 additions & 1 deletion places/views.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand Down

0 comments on commit 87ca86b

Please sign in to comment.