Python 如何使用django将数据插入表中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23560665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to insert data into table using django
提问by pramod24
I am new in django, and I am creating table in postgresql. I want to perform insert, update and delete operation using django. I want creating followng code.
我是 Django 新手,我正在 postgresql 中创建表。我想使用 django 执行插入、更新和删除操作。我想创建以下代码。
Models.py
模型.py
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
def __str__(self):
return ' '.join([
self.name,
self.address,
])
viwes.py
视图.py
def pramod(request):
if 'pname' in request.GET and request.GET['pname']:
p1 = request.GET['pname']
if 'address' in request.GET and request.GET['address']:
p2 = request.GET['address']
books = Publisher(name=p1,address=p2)
return render(request, 'Publisher.html',{'books': books})
回答by cor
This is the minimum code you need. Then you can add fields verification, or whatever you need:
这是您需要的最少代码。然后您可以添加字段验证,或您需要的任何内容:
publisher = Publisher(name=p1,address=p2)
publisher.save()
回答by dannymilsom
You need to create an instance of the model class (Publisher in this case), instantiate it with the appropriate values (name and address) and then call save(), which composes the appropriates SQL INSERTstatement under the hood.
您需要创建模型类的实例(在本例中为 Publisher),使用适当的值(名称和地址)对其进行实例化,然后调用save(),它在幕后组成了适当的 SQLINSERT语句。
book = Publisher(name=p1, address=p2)
book.save()
I recommend you read the model docs.
我建议您阅读模型文档。

