Filtering models in view

Hello everyone,

I have a question that is probably pretty basic.
I have a SQLite database that looks like this:

from django.db import models


# Create your models here.
class Company(models.Model):
    title = models.CharField(max_length=200)
    address = models.CharField(max_length=200)
    post_office = models.CharField(max_length=200)
    ddv_id = models.CharField(max_length=200)

    def __str__(self):
        return self.title


class Bill(models.Model):
    eor = models.CharField(max_length=100, primary_key=True)
    producer = models.ForeignKey(Company, on_delete=models.CASCADE)
    bill_number = models.CharField(max_length=200)
    seller = models.CharField(max_length=200)
    last_updated = models.DateTimeField('last updated')
    tax_level = models.FloatField()
    zoi = models.CharField(max_length=200)
    status = models.BooleanField()

    def __str__(self):
        return self.eor


class Product(models.Model):
    bill = models.ForeignKey(Bill, on_delete=models.CASCADE)
    product_title = models.CharField(max_length=200)
    quantity = models.IntegerField()
    value = models.FloatField()

    def __str__(self):
        return self.product_title

In HTML (localhost/app/bill_eom/products), where bill_eom is primary key of Bill model.
I want to display only products, that are associated with that bill.
I have hard coded a bill_eom in view for demonstration:

class ProductsView(generic.ListView):
    template_name = 'app/bill_products.html'
    context_object_name = 'product_list'

    def get_queryset(self):
        return Product.objects.filter(bill__eor="af4c16cf-7d92-fcbb-98b7-9c8f4acd81bb") # yes, this is bill's primary key

Then, there’s url side:

path('<str:bill_id>/products', views.ProductsView.as_view(), name='product')

and this is HTML side:

{% for product in product_list %}
        <p>{{ product.product_title }}</p>
{% endfor %}

Thank you all alot in advance

You’re really close here.

In a CBV, the url parameters are stored in self.kwargs. So at any point in your CBV, you can reference that parameter as self.kwargs['bill_id'], making your get_queryset look something like this:

def get_queryset(self):
        return Product.objects.filter(bill__eor=self.kwargs['bill_id']) 

2 Likes

Thank you so much Ken. Now it works perfectly :slight_smile: