get() से एक Single Object प्राप्त करना
try:
obj = ModelName.objects.get(field=value)
except ModelName.DoesNotExist:
# handle missing object
एक Object Fetch करना
Model.objects.get(field=value) exactly एक matching object directly return करता है — एक QuerySet में wrapped नहीं — जब आप sure हों कि सिर्फ एक row match करता है।
उदाहरण: Fetching One Object
Model.objects.get(field=value) returns exactly one matching object directly — not wrapped in a QuerySet — when you're sure only one row matches.
book = Book.objects.get(id=1)
print(book.title)
⚠️ Run this in your own terminal or Node.js environment.
एक Missing Object Handle करना
अगर कोई row condition match नहीं करती, .get() Book.DoesNotExist raise करता है। उस case को gracefully handle करने के लिए इसे try/except में wrap करें।
उदाहरण: Handling a Missing Object
If no row matches the condition, .get() raises Book.DoesNotExist. Wrap it in a try/except to handle that case gracefully.
try:
book = Book.objects.get(id=999)
except Book.DoesNotExist:
print('No book with that id')
⚠️ Run this in your own terminal or Node.js environment.
बहुत ज़्यादा Matches Handle करना
अगर एक से ज़्यादा row condition match करती है, .get() silently एक चुनने के बजाय Book.MultipleObjectsReturned raise करता है।
उदाहरण: Handling Too Many Matches
If more than one row matches the condition, .get() raises Book.MultipleObjectsReturned instead of silently picking one.
try:
book = Book.objects.get(genre='Action')
except Book.MultipleObjectsReturned:
print('More than one match')
⚠️ Run this in your own terminal or Node.js environment.
- एक condition पर .get() उपयोग करना जो zero या कई rows match कर सकता है, जो DoesNotExist या MultipleObjectsReturned raise करता है।
- जब object exist न हो सकता है तो .get() को try/except में wrap न करना, पूरे view को crash करते हुए।
- एक समय में एक related object fetch करने के लिए एक loop के अंदर .get() उपयोग करना, एक single filter या select_related उपयोग करने के बजाय।
- Model.objects.get(...) exactly एक object return करता है, एक QuerySet नहीं।
- अगर कोई object match नहीं करता, Django Model.DoesNotExist raise करता है।
- अगर एक से ज़्यादा object match करता है, Django Model.MultipleObjectsReturned raise करता है।
- get() एक unique field के साथ उपयोग करना सबसे अच्छा है, जैसे primary key या एक id, एक single match guarantee करने के लिए।
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: