Sobes.tech
Junior

How do you create an object in Django ORM?

sobes.tech AI

Answer from AI

Create an instance of the model, then call the save() method.

# Import the model
from myapp.models import MyModel

# Create an instance of the model
obj = MyModel(field1='value1', field2='value2')

# Save the object to the database
obj.save()

You can also use the model manager objects.create():

# Import the model
from myapp.models import MyModel

# Create and save the object in one operation
obj = MyModel.objects.create(field1='value1', field2='value2')

When using create(), the object is immediately saved to the database.