python
46 lines · 1 tab
Priya Sharma
Jan 2026
1 tab
from django.db.models import Q
from django.views.generic import ListView
from .models import Product
class ProductSearchView(ListView):
model = Product
template_name = 'products/search.html'
context_object_name = 'products'
def get_queryset(self):
query = self.request.GET.get('q', '')
if not query:
return Product.objects.none()
# Search in multiple fields with OR
search_query = Q(name__icontains=query) | \
Q(description__icontains=query) | \
Q(category__name__icontains=query)
# Filter active products only
active_query = Q(is_active=True)
# Combine with AND
return Product.objects.filter(search_query & active_query).distinct()
def filter_products(request):
"""Dynamic filtering based on request params."""
filters = Q()
# Add filters conditionally
if min_price := request.GET.get('min_price'):
filters &= Q(price__gte=min_price)
if max_price := request.GET.get('max_price'):
filters &= Q(price__lte=max_price)
if category := request.GET.get('category'):
filters &= Q(category__slug=category)
# Exclude out of stock
filters &= ~Q(stock=0)
return Product.objects.filter(filters)
1 file · python
Explain with highlit
Q objects enable complex query logic with OR, AND, and NOT operations. I combine them with | for OR and & for AND. The ~Q() syntax negates a condition. This is cleaner than raw SQL for dynamic filters. I build Q objects conditionally based on user input, adding clauses as needed. For search across multiple fields, I chain Q objects with OR. Parentheses control precedence when mixing operators. Q objects work with all QuerySet methods like filter() and exclude(). This keeps queries readable and database-agnostic.
Related snips
python
import os
import stat
for root, _dirs, files in os.walk('/etc'):
for name in files:
path = os.path.join(root, name)
Python security audit script for exposed risky filesystem state
python
auditing
host-security
by Kai Nakamura
1 tab
python
class Product(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
cost = models.DecimalField(max_digits=10, decimal_places=2)
margin = models.DecimalField(max_digits=5, decimal_places=2, blank=True)
Django model signals vs overriding save
django
python
models
by Priya Sharma
2 tabs
python
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
Django URL namespacing and reverse lookups
django
python
urls
by Priya Sharma
3 tabs
ruby
# Vulnerable: user input is concatenated directly into SQL.
email = params[:email]
password = params[:password]
sql = "SELECT * FROM users WHERE email = '#{email}' AND password_hash = '#{password}'"
user = ActiveRecord::Base.connection.execute(sql).first
SQL injection prevention with unsafe and safe query patterns
sql-injection
owasp
database
by Kai Nakamura
3 tabs
python
import graphene
from graphene_django import DjangoObjectType
from blog.models import Post, Comment
class PostType(DjangoObjectType):
Django GraphQL with Graphene
django
python
graphql
by Priya Sharma
2 tabs
sql
-- EXPLAIN ANALYZE (actual execution statistics)
EXPLAIN ANALYZE
SELECT u.username, COUNT(o.id) AS order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at >= '2024-01-01'
Advanced query optimization techniques
database
optimization
query-performance
by Maria Garcia
2 tabs
Share this code
Here's the card — post it anywhere.