← Back to Django Course | Chapter 4: Models & Django ORM Basics | Lesson 6 of 10

QuerySets को Filter करना

Filtering filing cabinet को बताने जैसा है 'सिर्फ मुझे वे cards दिखाओ जहां name A से शुरू होता है', हर card table पर dump करने के बजाय।
Syntax
markup
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.

bash
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.

bash
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.

bash
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.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. .get() उपयोग करना जब कई rows match हो सकते हों, .filter() के बजाय, जो MultipleObjectsReturned raise करता है।
  2. अलग .filter() calls में unrelated conditions chain करना जब एक single combined filter ज़्यादा clear और तेज़ होता।
  3. .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 किया जा सकता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.