0

I am trying to write a search logic. but i am stuck here.

I have Location Model and Rate Model. Each Location can have multiple rates. these are classes

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)

now if the user search for location with rate 3, i will do this in view

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))

and in my template:

{% for loc in locations %}
  {{loc.rate.rate}} <--------- wrong! how to get that searched rate 3 here?? 
{% endfor %}

But since every location object can have multiple Rates, {{loc.rate.rate}} doesnot work. what i want is, to get that exactly wanted rate - here 3 which was searched for.

can someone give me some hint or help please.

many thanks

doniyor
  • 36,596
  • 57
  • 175
  • 260

1 Answers1

2

This should work -

{% for loc in locations %}
  {% for rate in loc.rate %}
    {{ rate.rate }}
  {% endfor %}
{% endfor %}
Bibhas Debnath
  • 14,559
  • 17
  • 68
  • 96
  • thanks, but then i can get more rates, right? since one location can have more rates... how can i get that location with that rate which was searched? – doniyor May 09 '13 at 17:06
  • `locations = Location.objects.filter(rate__rate=rate_from_get)`? And please use more explicit names. So that it's not confusing. – Bibhas Debnath May 09 '13 at 17:10
  • it is saying: RelatedManager is not iterable – doniyor May 09 '13 at 18:16
  • 1
    wherever it's saying that RelatedManager is not iterable, put a `.all()`(if in view) or `.all`(if in template) after it. Should work. – Bibhas Debnath May 09 '13 at 18:46
  • look, i decided to write a custom filter that takes a parameter, that parameter is the rate number which was searched. then the filter takes it and gets that rate from location which is rendered. am i okay with this? – doniyor May 09 '13 at 18:51
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/29688/discussion-between-doniyor-and-bibhas) – doniyor May 09 '13 at 18:51