【发布时间】:2014-08-19 19:19:08
【问题描述】:
我正在关注 Django 文档以构建多搜索条件表单。我的第一个问题是这是否应该是在查询中过滤值的正确方法,以及如何添加外键和 m2m 在搜索条件中显示为选择和多选。这是我到目前为止的代码。谢谢
表格
class SearchPropertyForm(forms.Form):
name = forms.CharField(max_length = 100, widget = forms.TextInput(attrs = {'class':'form-control', 'placeholder':'Nombre'}))
activity = forms.ModelChoiceField(queryset = Activity.objects.all(), widget = forms.Select(attrs = {'class':'form-control', 'placeholder':'Actividad'}))
currency = forms.ModelChoiceField(queryset = Currency.objects.all(), widget = forms.Select(attrs = {'class':'form-control', 'placeholder':'Moneda'}))
price_from = forms.IntegerField(widget = forms.TextInput(attrs = {'class':'form-control', 'placeholder':'Precio-Desde'}))
price_to = forms.IntegerField(widget = forms.TextInput(attrs = {'class':'form-control', 'placeholder':'Precio-Hasta'}))
categories = forms.ModelMultipleChoiceField(queryset = Category.objects.all(), widget = forms.SelectMultiple(attrs = {'class':'form-control', 'placeholder':'Categorias'}))
型号
class Property(models.Model):
class Meta:
verbose_name_plural = "properties"
name = models.CharField(max_length = 200)
description = models.TextField(max_length = 500)
address = models.CharField(max_length = 200)
sqft = models.DecimalField(max_digits = 6, decimal_places = 2)
beds = models.IntegerField()
baths = models.IntegerField()
status = models.BooleanField(default = True)
price = models.DecimalField(max_digits = 6, decimal_places = 2)
likes = models.IntegerField()
categories = models.ManyToManyField(Category, null = True, blank = True)
currency_type = models.ForeignKey(Currency)
activity_type = models.ForeignKey(Activity)
creation_date = models.DateTimeField(auto_now_add = True)
edition_date = models.DateTimeField(default = timezone.now)
def __unicode__(self):
return self.name
查看
def search_properties(request):
if request.method == 'POST':
form = SearchPropertyForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
activity = form.cleaned_data['activity']
currency = form.cleaned_data['currency']
price_from = form.cleaned_data['price_from']
price_to = form.cleaned_data['price_to']
categories = form.cleaned_data['categories']
properties = Property.objects.filter(name__icontains = name).filter(
activity_type__exact = int(activity)).filter(
currency_type__exact = int(currency)).filter(
price_from__gte = int(price_from)).filter(
price_from__lte = int(price_to)).filter(
categories__exact = int(categories))
return render(request, 'properties/search_properties.html', {
'properties': properties,
'media_url': settings.MEDIA_URL,
'form':form,
})
else:
form = SearchPropertyForm()
properties = Property.objects.filter(status = True)
return render(request, 'properties/search_properties.html', {
'properties': properties,
'media_url': settings.MEDIA_URL,
'form':form,
})
【问题讨论】:
标签: python django django-forms django-views