我正在尝试编写搜索逻辑。但我被困在这里
我有位置模型和费率模型。每个位置可以有多种费率。这些是类
class Location(models.Model):
name = models.TextField()
price = models.CharField(max_length=10)
class Rate(models.Model):
location = models.ForeignKey(Location,related_name="rate")
rate = models.IntegerField(max_length=10)
现在,如果用户搜索费率为3
的位置,我将在视图中执行此操作
def search(request):
rate = request.GET.get('get')
#all rates
allrates = Rate.objects.filter(rate=rate)
#all locations with this rate
locations = Location.objects.filter(rate__in=allrates)
return render_to_response('result.html',{'locations':locations},context_instance=RequestContext(request))
并在我的模板中:
{% for loc in locations %}
{{loc.rate.rate}} <--------- wrong! how to get that searched rate 3 here??
{% endfor %}
但由于每个位置对象都有多个速率,{{loc.rate.rate}}
不起作用。我想要的是,获得确切的通缉率 - 这里搜索的是3。
答案 0 :(得分:2)
这应该有效 -
{% for loc in locations %}
{% for rate in loc.rate %}
{{ rate.rate }}
{% endfor %}
{% endfor %}