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

Model Instances बनाना

एक model instance बनाना आपके form template की एक copy भरने और इसे filing cabinet में save करने जैसा है, जो यहां database है।
Syntax
markup
# 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.

bash
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 करते हुए।

Note: जब आपको object save करने से पहले बदलने की ज़रूरत न हो तो objects.create() prefer करें।

उदाहरण: 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.

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

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

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. Model(...) से एक object बनाना लेकिन .save() call करना भूल जाना, इसलिए यह असल में कभी database में नहीं लिखा जाता।
  2. एक field name pass करना जो model पर मौजूद नहीं, जो creation time पर एक TypeError raise करता है।
  3. 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 मिलती है।

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.