如何使用Django的ORM将一行数据插入表中

Joh*_*Doe 9 django django-models

如何使用Django ORM将Django中的数据插入到SQL表中?

ale*_*cxe 12

如果需要插入一行数据,请参阅模型上方法的" 保存对象 "文档save.

仅供参考,您可以执行批量插入.请参阅bulk_create方法的文档.


小智 7

如果您不想显式调用 save() 方法,可以使用以下方法创建记录MyModel.objects.create(p1=v1, p2=v1, ...)

fruit = Fruit.objects.create(name='Apple')
# get fruit id
print(fruit.id)
Run Code Online (Sandbox Code Playgroud)

查看文档


Roh*_*han 6

事实上,它是在" 编写你的第一个Django应用程序 "教程的第一部分中提到的.

正如"使用API​​"部分所述:

>>> from django.utils import timezone
>>> p = Poll(question="What's new?", pub_date=timezone.now())

# Save the object into the database. You have to call save() explicitly.
>>> p.save()

# Now it has an ID. Note that this might say "1L" instead of "1", depending
# on which database you're using. That's no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
>>> p.id
1
Run Code Online (Sandbox Code Playgroud)

本教程的第4部分介绍了如何使用表单以及如何使用用户提交的数据保存对象.