2

I'm sorry if this is a stupid question, but I'm having trouble finding out how to create a new instance of a model inside the views.

Referencing this question, I tried doing

foo = FooModel() save() 

but I got a NameError: name 'save' is not defined. I then tried

bar = BarModel.objects.create() 

but got AttributeError: 'Manager' object has no attribute 'Create'.

Am I not understanding something very trivial? Maybe those commands are just for the command line? In that case, how do I create new objects, or filter them, etc... from code?

3 Answers 3

6

For the first example, you need to call the save method on the object, e.g. foo.save() instead of just save():

foo = FooModel() foo.save() 

Your second example looks ok. Make sure you are calling create() (all lowercase):

bar = BarModel.objects.create() 

The message ... no attribute 'Create'. suggests you are calling BarModel.objects.Create(), which is incorrect.

If that still doesn't work, then update your question with the actual code and full traceback. Using made up names like FooModel makes it harder to see the problem.

Sign up to request clarification or add additional context in comments.

3 Comments

If I do the second way, will any parameter I specify for that object be automatically saved? Like if I do bar.name='emerald' #implying the model has an attribute name
bar.name='emerald' just sets the attribute. It won’t be saved to the database until you call bar.save(). However you can do bar = BarModel.objects.create(name='emerald') to create and save an object with that name.
I did the second thing you suggested in the end, thanks.
4

save is method of instance, should be:

foo = FooModel() foo.save() 

Comments

0

To create a new instance of a object from your models you do like that:

models.py

class Test(models.Model): id = models.AutoField(primary_key=True) 

views.py

test = Test() 

You can also use the constructor:

test = Test(id=3) test.save() # save object to database test.objects.filter(id=3) # get object from database 

1 Comment

Test(id=3) isn’t a good example - usually you should let the database set the primary key automatically.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.