Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create model instances from command line (terminal)

I thought this would have been a previously asked question, so maybe I'm not phrasing it right.

I tried:

manage.py python3.6 dbshell

and then:

 obj= Person.objects.create('Justin')

but this did not work. Thanks for any help.

like image 995
justin Avatar asked Aug 13 '18 18:08

justin


2 Answers

You are on the right track, but when you create model instances, you should use named parameters for the fields, so for example:

obj = Person.objects.create(name='Justin')

(given of course a Person has a name field)

This is logical since a model can have several fields, and there is no "inherent" order.

Using positional parameters would be very risky, since a simply "reshuffle" of the fields would result in model object constructions going wrong.

like image 182
Willem Van Onsem Avatar answered Oct 17 '22 06:10

Willem Van Onsem


dbshell command runs the command-line client for the database, so you'd have to use SQL to create a row in your database using that. What you actually want is the shell command. It opens a Python interpreter with Django configured, so you can work with ORM there.

like image 27
mateuszb Avatar answered Oct 17 '22 06:10

mateuszb