简体   繁体   中英

How do I create an instance of a model in views.py?

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?

For the first example, you need to call the save method on the object, eg 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.

save is method of instance, should be:

foo = FooModel()
foo.save()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM