Filter list with db model
This commit is contained in:
@ -1,27 +1,31 @@
|
||||
from typing import Any, Optional
|
||||
|
||||
from project.main.cat_breeds import CatBreed, cat_breeds
|
||||
from django.db.models import Count, Q
|
||||
|
||||
from project.main.models import CatBreed
|
||||
from project.main.views.demo_view_base import DemoViewBase
|
||||
|
||||
|
||||
def get_countries() -> list[str]:
|
||||
return sorted(set([c.country for c in cat_breeds if len(c.country)]))
|
||||
ann = (
|
||||
CatBreed.objects.values("country")
|
||||
.annotate(Count("country"))
|
||||
.order_by("country")
|
||||
)
|
||||
return [a["country"] for a in ann]
|
||||
|
||||
|
||||
def filter_cat_breeds(
|
||||
breed_filter: Optional[str] = None, country_filter: Optional[str] = None
|
||||
) -> list[CatBreed]:
|
||||
if not breed_filter and not country_filter:
|
||||
return cat_breeds
|
||||
q = Q()
|
||||
|
||||
result = []
|
||||
for breed in cat_breeds:
|
||||
# if (not breed_filter or breed_filter.lower() in breed.name.lower()) or (
|
||||
# not country_filter or country_filter == breed.country
|
||||
# ):
|
||||
if not breed_filter or breed_filter.lower() in breed.name.lower():
|
||||
result.append(breed)
|
||||
return result
|
||||
if breed_filter:
|
||||
q &= Q(name__icontains=breed_filter)
|
||||
if country_filter:
|
||||
q &= Q(country=country_filter)
|
||||
|
||||
return CatBreed.objects.filter(q).order_by("name")
|
||||
|
||||
|
||||
class FilterListView(DemoViewBase):
|
||||
|
||||
Reference in New Issue
Block a user