Model Instances बनाना
# Two steps
obj = ModelName(field=value)
obj.save()
# One step
obj = ModelName.objects.create(field=value)
Two-Step Creation
आप पहले memory में एक instance बना सकते हैं, फिर इसे असल में database में लिखने के लिए अलग से .save() call कर सकते हैं।
उदाहरण: Two-Step Creation
You can build an instance in memory first, then call .save() separately to actually write it to the database.
book = Book(title='Django Basics', pages=250)
book.save()
print(book.id)
⚠️ Run this in your own terminal or Node.js environment.
create() के साथ One-Step Creation
Model.objects.create(...) एक ही call में instance बनाता है और इसे database में save करता है, नया object return करते हुए।
उदाहरण: One-Step Creation with create()
Model.objects.create(...) builds the instance and saves it to the database in a single call, returning the new object.
book = Book.objects.create(title='Learn Django', pages=180)
print(book.id)
⚠️ Run this in your own terminal or Node.js environment.
इसे Django Shell में चलाना
Django shell आपको अपनी असली database के against interactively model creation try करने देता है, जो ORM सीखते समय useful है।
उदाहरण: Running It in the Django Shell
The Django shell lets you try model creation interactively against your real database, which is useful while learning the ORM.
python manage.py shell
>>> from myapp.models import Book
>>> Book.objects.create(title='Shell Demo', pages=90)
⚠️ Run this in your own terminal or Node.js environment.
- Model(...) से एक object बनाना लेकिन .save() call करना भूल जाना, इसलिए यह असल में कभी database में नहीं लिखा जाता।
- एक field name pass करना जो model पर मौजूद नहीं, जो creation time पर एक TypeError raise करता है।
- Bulk data के लिए एक loop के अंदर .save() बार-बार call करना bulk_create उपयोग करने के बजाय, कई slow, separate database writes का कारण बनते हुए।
- आप model class को field values के साथ keyword arguments के रूप में instantiate करके एक नया row बनाते हैं।
- .save() call करना उस instance को database में एक नए row के रूप में लिखता है।
- Model.objects.create(...) दोनों steps — build और save — एक ही call में करता है।
- हर saved instance को Django से अपने आप एक unique id मिलती है।
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: