Quantcast
Channel: Active questions tagged listview - Stack Overflow
Viewing all articles
Browse latest Browse all 611

Django queryset not filtering correctly in ListView with complex lookup

$
0
0

I'm trying to build a Django application where I have a ListView that displays a list of objects based on complex filtering criteria, but I'm encountering issues with the queryset not filtering correctly. Here's a simplified version of my code:

models.py

from django.db import modelsclass Product(models.Model):    name = models.CharField(max_length=100)    price = models.DecimalField(max_digits=10, decimal_places=2)    category = models.CharField(max_length=100)    stock_quantity = models.IntegerField()class Sale(models.Model):    product = models.ForeignKey(Product, on_delete=models.CASCADE)    quantity_sold = models.IntegerField()    sale_date = models.CharField()

views.py

from django.views.generic import ListViewfrom .models import Product, Saleclass ProductListView(ListView):    model = Product    template_name = 'product_list.html'    def get_queryset(self):        queryset = super().get_queryset()        return queryset.filter(category='Electronics', stock_quantity__gte=10, sale__sale_date__month=4)

product_list.html

{% extends 'base.html' %}{% block content %}<h1>Products</h1><ul>        {% for product in object_list %}<li>{{ product.name }}</li>        {% endfor %}</ul>{% endblock %}

I expect this ProductListView to display a list of products that belong to the 'Electronics' category, have a stock quantity of at least 10, and have had sales in the current month (April). However, when I visit the page, it displays an empty list, even though I know there are products that meet these criteria.

I've tried debugging by printing the queryset in the get_queryset method, and it seems to be filtering correctly. I'm not sure what's going wrong or how to fix it.

Can someone please help me understand why the queryset is not filtering correctly in the ListView and how I can resolve this issue? Any insights or suggestions would be greatly appreciated. Thank you!"


Viewing all articles
Browse latest Browse all 611

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>