Heads up! To view this whole video, sign in with your Courses Plus account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Sometimes we need to create a model instance outside of a model form. Or, sometimes, we need to create several model instances at once. Let's see how the ORM handles both of these situations.
Docs on .create()
, .bulk_create()
, and get_or_create()
.
When you're using get_or_create()
, you'll probably want to assign the object that comes back and the boolean for whether or not it was created in some variables.
course, created = Course.objects.get_or_create(title="REST API Basics")
will divide up the values for you, into the two variables. If you don't need the created
value, though, you can just throw it away with an underscore: course, _ = Course.objects.get_or_create(title="REST API Basics")
.
You need to sign up for Treehouse in order to download course files.
Sign up