2
我有兩個類位置和供應商。供應商將其產品供應給一個或多個城市。過濾Django中的多對多關係
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)
現在我必須從城市列表中獲取城市的所有供應商。例如:如果倫敦被點擊,我應該得到所有與倫敦有關的供應商。我應該怎麼做?
Supplier.objects.filter(supplied_cities= 1)
以上shell命令列出來自城市1(int)的所有供應商。但是我必須從網頁捕捉城市名稱並根據它進行過濾?
查看:
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))
模板:
{% for sellers in object_list %}
<li> {{ sellers.name }} </li>
{% endfor %}
謝謝。過濾器在shell命令中工作。我應該如何創建網址?例如,目前我正在使用http://127.0.0.1:8000/locations/search/london/,但它看起來像上下文變量「賣家」總是空的。 – Robby
謝謝。有效。 – Robby