QuerySets को Filter करना
In this page:
ModelName.objects.filter(field=value)
ModelName.objects.filter(field1=value1, field2=value2) # AND
ModelName.objects.exclude(field=value)
Basic Filtering
Model.objects.filter(field=value) सिर्फ उन rows को return करता है जहां वह field given value से match करता है, एक नए QuerySet के रूप में।
उदाहरण: Basic Filtering
Model.objects.filter(field=value) returns only the rows where that field matches the given value, as a new QuerySet.
action_books = Book.objects.filter(genre='Action')
for book in action_books:
print(book.title)
⚠️ Run this in your own terminal or Node.js environment.
Multiple Fields पर Filtering
.filter() को कई keyword arguments pass करना उन्हें AND logic के साथ combine करता है — हर condition match होना चाहिए।
उदाहरण: Filtering on Multiple Fields
Passing multiple keyword arguments to .filter() combines them with AND logic — every condition must match.
books = Book.objects.filter(genre='Action', pages__gt=100)
for book in books:
print(book.title, book.pages)
⚠️ Run this in your own terminal or Node.js environment.
Filters Chain करना
क्योंकि .filter() एक QuerySet return करता है, आप result पर फिर से .filter() call कर सकते हैं step by step और conditions add करने के लिए।
उदाहरण: Chaining Filters
Because .filter() returns a QuerySet, you can call .filter() again on the result to add more conditions step by step.
qs = Book.objects.filter(genre='Action')
qs = qs.filter(pages__gt=100)
print(qs.count())
⚠️ Run this in your own terminal or Node.js environment.
- .get() उपयोग करना जब कई rows match हो सकते हों, .filter() के बजाय, जो MultipleObjectsReturned raise करता है।
- अलग .filter() calls में unrelated conditions chain करना जब एक single combined filter ज़्यादा clear और तेज़ होता।
- .all() से सब कुछ fetch करने के बाद Python में filter करना, database को .filter() से filtering करने देने के बजाय।
- .filter(field=value) एक QuerySet return करता है जिसमें सिर्फ वे rows हैं जो condition match करते हैं।
- आप एक साथ कई keyword arguments pass करके multiple fields पर filter कर सकते हैं।
- Filtering database में होती है, जो Python में filtering करने से कहीं ज़्यादा efficient है।
- Filters को progressively एक QuerySet narrow down करने के लिए साथ chain किया जा सकता है।
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: