objects.all() से Query करना
In this page:
queryset = ModelName.objects.all()
for obj in queryset:
# use obj.field_name
हर Row Fetch करना
Model.objects.all() एक QuerySet return करता है जो उस model की table में हर row represent करता है, उस order में जिसमें database उन्हें return करता है (या Meta.ordering अगर set हो)।
उदाहरण: Fetching Every Row
Model.objects.all() returns a QuerySet representing every row in that model's table, in the order the database returns them (or Meta.ordering if set).
books = Book.objects.all()
for book in books:
print(book.title)
⚠️ Run this in your own terminal or Node.js environment.
QuerySets Lazy हैं
.all() call करना database को तुरंत hit नहीं करता। Django असली SQL query सिर्फ तब चलाता है जब आप QuerySet पर iterate करें, इसे print करें, या इसे एक list में convert करें।
उदाहरण: QuerySets Are Lazy
Calling .all() doesn't hit the database right away. Django only runs the actual SQL query the moment you iterate over the QuerySet, print it, or convert it to a list.
qs = Book.objects.all()
print('query not run yet')
for book in qs:
print(book.title)
⚠️ Run this in your own terminal or Node.js environment.
Results Count करना
एक QuerySet पर .count() call करना database को rows directly count करने के लिए कहता है, जो हर row सिर्फ len() measure करने के लिए fetch करने से तेज़ है।
उदाहरण: Counting Results
Calling .count() on a QuerySet asks the database to count rows directly, which is faster than fetching every row just to measure len().
total = Book.objects.all().count()
print(total)
⚠️ Run this in your own terminal or Node.js environment.
- list(Model.objects.all()) unnecessarily call करना, यह भूल जाना कि एक QuerySet खुद से ही पहले से iterable है।
- यह मान लेना कि Model.objects.all() results तुरंत return करता है, जब यह असल में lazy है और सिर्फ तब database hit करता है जब आप इसे iterate या evaluate करें।
- इसे Python में filter करने के लिए एक बड़े objects.all() result पर loop करना, .filter() के साथ database में filter करने के बजाय।
- Model.objects.all() एक QuerySet return करता है जिसमें उस model की table में अभी मौजूद हर row शामिल है।
- QuerySets lazy होते हैं — database query सिर्फ तभी चलती है जब results असल में उपयोग किए जाएं।
- आप एक QuerySet पर directly एक for loop से loop कर सकते हैं, बिल्कुल एक list जैसा।
- objects वह default manager है जो Django हर model पर अपने आप attach करता है।
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: