Ali Raza Javeed
Ali Raza Javeed

Reputation: 155

one to Many relationship in Django

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

Answers (2)

Arjun Shahi
Arjun Shahi

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

willeM_ Van Onsem
willeM_ Van Onsem

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 Products (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

Related Questions