Reputation: 155
I have two models with one to many relations such as
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)
its url
path('speciality/<int:pk>',views.SpecialityDetailView.as_view(),name = 'speciality_product'),
and here is CBV
class SpecialityProductView(generic.ListView):
model = Product
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['product_list'] = self.object.category_id.all()
return context
I want products list based on specifinc Speciality
Upvotes: 1
Views: 124
Reputation: 7330
You need to use DetailView instead of ListView
like this
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
Upvotes: 1
Reputation: 476557
I want products list based on specific
Speciality
.
Then this looks more like a DetailView
[Django-doc] where you pass to your context the list of related Product
s (or just render these in your template):
class SpecialityProductView(generic.detail.DetailView):
model = Speciality
template_name = 'app/speciality.html'
In the template, you can then render this as:
<!-- app/speciality.html -->
{{ speciality.name }}
{% for product in speciality.product_set.all %}
{{ product.name }}
{% endfor %}
Upvotes: 1