从多对多关系中获取数据(中间表)

时间:2012-12-10 09:16:08

标签: python django many-to-many

我已经设置了几个模型如下:

产品

分类

产品和类别分享多对多关系,这使得第三个表 product_categories 保存了产品ID和类别ID。

我想按类别显示产品列表。*强调文字*我现在我有类别ID但我不知道如何从这个M2M中间表中获取数据。

所以请建议我这样做。

感谢。

被修改

我试过这个东西

我的模特

class Product():
    image = CharField(_("Image"), max_length=100, blank=True, null=True)
    style_idea = models.TextField(_("style idea"), blank=True)
    categories = models.ManyToManyField("Category", blank=True,
                                    verbose_name=_("Product categories"))

我的视图

if page.id == 11:
            value = Category.objects.all()
            value2 = Product.objects.all()
            value1 = ProductVariation.objects.all()
            return render_to_response('boutique.html',{'page':page,'productvariation':value1,'category':value,'products':value2} , context_instance=RequestContext(request))

我的模板

{% regroup products by category as products_by_category %}
{% for c in products_by_category %}
{{c}}
{%endfor%}  

此c打印所有产品

1 个答案:

答案 0 :(得分:1)

通常你会做类似

的事情
category = Category.objects.get(pk=10)
products = category.product_set.all()  # note that this is a queryset
相关问题