Robby
Robby

Reputation: 401

Filtering in Many to Many relationship in django

I have two classes Location and Supplier. A supplier supplies its products to one or more cities.

class Location(models.Model):
    cities = models.CharField(max_length=30)

class Supplier(models.Model):
    name = models.CharField(max_length=100)
    supplied_cities = models.ManyToManyField(Location)

Now I have to get all the Suppliers for a city, from a list of Cities. for example: If London is clicked, I should get the all the suppliers related to London. How should I do this?

Supplier.objects.filter(supplied_cities= 1)

Above shell command lists all suppliers from city 1 (int). But I have to capture the City Name from the web page and filter based on it?

View:

def my_view(request):
    cityName = request.GET['place']
    sellers = Supplier.objects.filter(supplied_cities= Location.objects.get(cities=cityName))
    context = {'sellers' : sellers }
    return render_to_response('results.html',context,context_instance=RequestContext(request))

Template:

{% for sellers in object_list %}
<li>  {{ sellers.name }} </li>
{% endfor %}

Upvotes: 2

Views: 224

Answers (1)

Josh Smeaton
Josh Smeaton

Reputation: 48730

You want to use lookups that span relationships:

def my_view(request):
    city_name = request.GET.get('place')
    sellers = Supplier.objects.filter(supplied_cities__cities=city_name)
    context = {'sellers' : sellers }
    return render_to_response('results.html', context, context_instance=RequestContext(request))

And then your template:

{% for seller in sellers %}
    <li>  {{ seller.name }} </li>
{% endfor %}

You misnamed your context variable.

I also highly recommend either using django forms or the url dispatcher for passing arguments to your views.

url(r'^/sellers/(?P<city>\w+)/$', my_view, name='sellers')

def my_view(request, city):
    # rest of your view

Upvotes: 2

Related Questions