简体   繁体   English

如何在views.py中创建模型的实例?

[英]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. 但我收到一个NameError:未定义名称“保存”。 I then tried 然后我尝试

bar = BarModel.objects.create()

but got AttributeError: 'Manager' object has no attribute 'Create'. 但出现AttributeError:“ Manager”对象没有属性“ 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() : 对于第一个示例,您需要在对象上调用save方法,例如foo.save()而不是save()

foo = FooModel()
foo.save()

Your second example looks ok. 您的第二个示例看起来还可以。 Make sure you are calling create() (all lowercase): 确保您正在调用create() (全部为小写):

bar = BarModel.objects.create()

The message ... no attribute 'Create'. 消息... no attribute 'Create'. suggests you are calling BarModel.objects.Create() , which is incorrect. 建议您调用BarModel.objects.Create() ,这是不正确的。

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. 使用像FooModel这样的FooModel名称将使问题更难发现。

save is method of instance, should be: save是实例的方法,应为:

foo = FooModel()
foo.save()

To create a new instance of a object from your models you do like that: 要从模型中创建对象的新实例,您需要执行以下操作:

models.py models.py

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

views.py 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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