gpt4 book ai didi

python - Django 高级搜索

转载 作者:太空宇宙 更新时间:2023-11-04 01:09:50 25 4
gpt4 key购买 nike

我目前正在通过制作一个销售二手自行车的网络应用程序来学习 Django,但我在现场搜索方面遇到了问题。我想为每个模型字段都有一个搜索字段,但我不知道该怎么做。最好的方法是什么?我们非常欢迎任何帮助!

这是我的模型:

class UsedBike(models.Model):
manufacturers = (
('Aprilia', 'Aprilia'),
('Benelli', 'Benelli'),
('BMW', 'BMW'),
('Cagiva', 'Cagiva'),
('Gilera', 'Gilera'),
('Harley-Davidson', 'Harley-Davidson'),
('Husaberg', 'Husaberg'),
('Husquarna', 'Husquarna'),
('Hyosung', 'Hyosung'),
('Kawasaki', 'Kawasaki'),
('KTM', 'KTM'),
('Kymco', 'Kymco'),
('Moto Guzzi', 'Moto Guzzi'),
('MV Agusta', 'MV Agusta'),
('Suzuki', 'Suzuki'),
('Tomos', 'Tomos'),
('Triumph', 'Triumph'),
('Yamaha', 'Yamaha'),
)
manufacturer = models.CharField(help_text = 'Manufacturer: ',
max_length = 20,
choices = manufacturers)
model = models.CharField(max_length = 20, help_text = 'Model: ')

最佳答案

我解决了这个但是我忘了贴出答案,这样任何有类似问题的人都可以使用它。它并不完美,但对我有用,如果有人有更好的解决方案,请随时回答。

在我的模型中我有:

class UsedBike(models.Model):

manufacturer = models.CharField(max_length = 20)
model = models.CharField(max_length = 20)
year = models.PositiveIntegerField(default = 0)
bike_type = models.CharField(max_length = 20)
price = models.PositiveIntegerField(default = 0)
engine_size = models.PositiveIntegerField(default = 0)

在 View 中:

def searchbike(request):

man = request.GET.get('manufacturer')
mod = request.GET.get('model')
year_f = request.GET.get('year_from')
year_t = request.GET.get('year_to')
price_f = request.GET.get('price_from')
price_t = request.GET.get('price_to')
bike_t = request.GET.get('bike_type')
capacity_f = request.GET.get('cubic_capacity_from')
capacity_t = request.GET.get('cubic_capacity_to')

question_set = UsedBike.objects.filter()

if request.GET.get('manufacturer'):
question_set = question_set.filter(manufacturer__exact = man)

if request.GET.get('model'):
question_set = question_set.filter(model__icontains = mod)

if request.GET.get('year_from'):
question_set = question_set.filter(year__gte = year_f)

if request.GET.get('year_to'):
question_set = question_set.filter(year__lte = year_t)

if request.GET.get('price_from'):
question_set = question_set.filter(price__gte = price_f)

if request.GET.get('price_to'):
question_set = question_set.filter(price__lte = price_t)

if request.GET.get('bike_type'):
question_set = question_set.filter(bike_type__exact = bike_t)

if request.GET.get('cubic_capacity_from'):
question_set = question_set.filter(engine_size__gte = capacity_f)

if request.GET.get('cubic_capacity_to'):
question_set = question_set.filter(engine_size__lte = capacity_t)

return render(request, 'shop/search.html', { 'searched': question_set})

关于python - Django 高级搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28356688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com