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?

Eärendil Baggins
  • 552
  • 1
  • 8
  • 23

3 Answers3

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.

Eärendil Baggins
  • 552
  • 1
  • 8
  • 23
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • 1
    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` – Eärendil Baggins Feb 16 '18 at 17:58
  • 1
    `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. – Alasdair Feb 16 '18 at 18:46
  • I did the second thing you suggested in the end, thanks. – Eärendil Baggins Feb 16 '18 at 18:49
4

save is method of instance, should be:

foo = FooModel()
foo.save()
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
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
  • `Test(id=3)` isn’t a good example - usually you should let the database set the primary key automatically. – Alasdair Feb 16 '18 at 18:43