【问题标题】:Filtering in Many to Many relationship in django在 django 中过滤多对多关系
【发布时间】:2012-12-13 19:05:46
【问题描述】:

我有两个类位置和供应商。供应商向一个或多个城市供应其产品。

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 %}

【问题讨论】:

    标签: python django


    【解决方案1】:

    你想使用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))
    

    然后是你的模板:

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

    您错误地命名了上下文变量。

    我还强烈建议使用django formsurl dispatcher 将参数传递给您的视图。

    url(r'^/sellers/(?P<city>\w+)/$', my_view, name='sellers')
    
    def my_view(request, city):
        # rest of your view
    

    【讨论】:

    • 谢谢。过滤器在 shell 命令中工作。我应该如何创建 URL?例如,目前我正在使用127.0.0.1:8000/locations/search/london,但看起来上下文变量“卖家”始终为空。
    猜你喜欢
    • 2020-06-18
    • 1970-01-01
    • 2023-03-06
    • 2011-02-27
    • 2011-12-08
    • 2021-03-19
    • 1970-01-01
    • 2020-10-15
    相关资源
    最近更新 更多