Django中的一对多关系

Django中的一对多关系,django,django-views,Django,Django Views,我有两个具有一对多关系的模型,例如 class Speciality(models.Model): name = models.CharField(max_length = 256) code = models.CharField(max_length = 256) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length = 256) code

我有两个具有一对多关系的模型,例如

class Speciality(models.Model):
name = models.CharField(max_length = 256)
code = models.CharField(max_length = 256)
def __str__(self):
    return self.name

class Product(models.Model):
name = models.CharField(max_length = 256)
code = models.CharField(max_length = 256)
reg_code = models.CharField(max_length = 256)
packe_size = models.CharField(max_length = 256)
type = models.CharField(max_length = 256)
category = models.ForeignKey(Speciality, on_delete=models.CASCADE)
它的网址

path('speciality/<int:pk>',views.SpecialityDetailView.as_view(),name = 'speciality_product'),
我想要基于特定专业的产品列表

您需要使用,而不是像这样使用
列表视图

class SpecialityProductView(generic.DetailView):
型号=专业
def获取上下文数据(自身,**kwargs):
context=super()。获取上下文数据(**kwargs)
context['product_list']=self.object.product_set.all()
返回上下文

我想要基于特定专业的产品列表

然后,这看起来更像是将相关
产品
列表传递给上下文(或仅在模板中呈现):

class SpecialityProductView(generic.detail.DetailView):
型号=专业
模板名称='app/speciality.html'
在模板中,可以将其渲染为:

<!-- app/speciality.html -->
{{ speciality.name }}
{% for product in speciality.product_set.all %}
    {{ product.name }}
{% endfor %}

{{speciality.name}
{speciality.product_set.all%}
{{product.name}

{%endfor%}
那么它看起来更像是一个
详细视图
,您可以在其中向上下文传递一个额外的列表。@WillemVanOnsem我也使用DetalView而不是ListView,但它不起作用,它不返回任何内容
    class SpecialityProductView(generic.DetailView):
        model = Speciality
        def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            context['product_list'] = self.object.product_set.all()
            return context
class SpecialityProductView(generic.detail.DetailView):
    model = Speciality
    template_name = 'app/speciality.html'
<!-- app/speciality.html -->
{{ speciality.name }}
{% for product in speciality.product_set.all %}
    {{ product.name }}
{% endfor %}