S
S
Suinny2020-06-05 19:41:46
Django
Suinny, 2020-06-05 19:41:46

How to make a model field filter by choices?

I'm doing a model filter, Filtering works fine on the normal field of the model. But it doesn't work in a field with a pre-set list of choices. How can this be implemented with standard django tools or third-party tools, if any?

models.py

CATEGORIES = [
        ('Центральный', 'Центральный'),
        ('Хостинский', 'Хостинский'),
        ('Адлерский', 'Адлерский'),
        ('Красная поляна', 'Красная поляна'),
    ]
    rayon = models.CharField(verbose_name='Район', choices=CATEGORIES, null=True, max_length=250)


forms.py
from django import forms

class Price(forms.Form):
    min_price = forms.IntegerField(label="от", required=False)
    max_price = forms.IntegerField(label="до", required=False)
    ordering = forms.ChoiceField(label="Сортировка", required=False, choices=[
        ['-timeStamp', 'по дате'],
        ['min_price_za_metr', 'дешевые сверху'],
        ['-min_price_za_metr', 'дорогие сверху'],
    ])


views.py
def blog_view(request):
    news = Post.objects.all()
    form = Price(request.GET)

    if form.is_valid():
        if form.cleaned_data["min_price"]:
            news = news.filter(min_price__gte=form.cleaned_data["min_price"])
        if form.cleaned_data["max_price"]:
            news = news.filter(min_price__lte=form.cleaned_data["max_price"])
        if form.cleaned_data["ordering"]:
            news = news.order_by(form.cleaned_data["ordering"])



    return render(request, 'novostroyki/blog.html', {'news':news, 'form':form})

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question