Фильтр по диапазону значений атрибута - PullRequest
0 голосов
/ 19 сентября 2019

У меня есть модель:

class Product(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField(null=True, blank=True)
    amount = models.IntegerField()
    price = models.FloatField()

Мне нужно создать фильтр по цене, чтобы я мог ввести диапазон цен (т.е. min_price = 10, max_price = 100), и он даст мне продукты сцена в этом диапазоне.

Есть ли способ сделать это в Django-admin (или Jet)?

Ответы [ 4 ]

1 голос
/ 19 сентября 2019

Возможно, в Django admin нет таких фильтров (я не уверен).Если есть опция, то вы должны настроить код.Но вы можете использовать в views.py и показать свои результаты.

products = Products.objects.filter(price__range=[min_price, max_price])

Как:

products = Products.objects.filter(price__range=[10, 100])
0 голосов
/ 19 сентября 2019

Вы можете использовать ModelAdmin и переопределить метод get_search_results, например:

# your_app/admin.py
from django.contrib import admin
from .models import Product

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ('title', 'amount', 'price')
    search_fields = ('title', 'price')  # this will create a text input for filtering title and price

    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super().get_search_results(request, queryset, search_term)

        # You need to define a character for splitting your range, in this example I'll use a hyphen (-)
        try:
            # This will get me the range values if there's only 1 hyphen
            min_price, max_price = search_term.split('-')
        except ValueError:
            # Otherwise it will do nothing
            pass
        else:
            # If the try was successful, it will proceed to do the range filtering
            queryset |= self.model.objects.filter(price__gte=min_price, price__lte=max_price)
        return queryset, use_distinct

Теперь, если я введу строку '20-25', он будет искать заголовок или цену, равную '20-25', затем ищите цену в диапазоне от 20 до 25. Если я введу строку '25', она будет искать цену или заголовок, равный '25', и передаст наш пользовательский фильтр.

Вы можете найти большеоб этом здесь это в документах.

0 голосов
/ 19 сентября 2019

Попробуйте это

    filtered_products = Product.objects.all().filter(price__range=(min_price, max_price))
0 голосов
/ 19 сентября 2019

Может быть django-admin-numeric-filter может помочь?

...