我有问题,因为我使用智能选择(3选择字段)来过滤我的表。但引擎id是错误的,没有得到正确的查询。我需要得到没有id从db,但常用名称。
views.py
def spec_list(request):
if request.method == 'GET':
form = SpecForm(request.GET)
if form.is_valid():
mark = form.cleaned_data['mark']
model = form.cleaned_data['model']
engine = form.cleaned_data['engine']
all_datap = Spec.objects.filter(mark=mark).filter(model=model).filter(engine=engine)
return render(request, 'specyfikacja/specyfikacja.html', {'form': form,'all_datap' : all_datap})
else:
form = SpecForm()
return render(request, 'specyfikacja/specyfikacja.html', {'form': form})
从mark = form.cleaned_data['mark']
我得到id为"1",但需要名称为"porshe"
models.py
from django.db import models
from smart_selects.db_fields import ChainedForeignKey
class Mark(models.Model):
mark = models.CharField(max_length = 60)
def __unicode__(self):
return unicode(self.mark)
class Model(models.Model):
mark = models.ForeignKey(Mark)
model = models.CharField(max_length = 300)
def __unicode__(self):
return unicode(self.model)
class Engine(models.Model):
model = models.ForeignKey(Model)
engine = models.CharField(max_length = 300)
def __unicode__(self):
return unicode(self.engine)
class Spec(models.Model):
mark = models.ForeignKey(Mark)
model = ChainedForeignKey(Model, chained_field = "mark", chained_model_field = "mark", show_all = False, auto_choose= True)
engine = ChainedForeignKey(Engine, chained_field = "model", chained_model_field = "model", auto_choose= True)
oe = models.CharField(max_length=4, null=True, blank=True)
plt = models.CharField(max_length=3, null=True, blank=True)
szer = models.CharField(max_length=5, null=True, blank=True)
series = models.CharField(max_length=5, null=True, blank=True)
zr = models.CharField(max_length=5, null=True, blank=True)
r = models.CharField(max_length=2, null=True, blank=True)
rim = models.CharField(max_length=5, null=True, blank=True)
def __unicode__(self):
return unicode(self.mark)
forms.py
class SpecForm(ModelForm):
class Meta:
model=Spec
fields = ('mark','model','engine')
模板<div class="subnav">
<div class="row-fluid">
<form action="" method="get">
<div class="span3">
{{ form.mark }}
</div>
<div class="span3">
{{ form.model }}
</div>
<div class="span3">
{{ form.engine }}
</div>
<div class="span1"><input class="btn btn-success" type="submit" value="Pobierz" /></div>
</form>
</div>
</div>
因为"engine"不是一个对象,只是一个字符串…试一试…
all_datap = Spec.objects.filter(mark__id=mark, model=model, engine__engine=engine).distinct()