Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Django 插入数据


添加记录

上一章中创建的 Members 表是空的。

我们将使用 Python 解释器(Python shell)向其中添加一些成员。

要打开 Python shell,请键入以下命令

py manage.py shell

现在我们进入了 shell,结果应该类似于以下内容

Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32
键入 "help"、"copyright"、"credits" 或 "license" 以获取更多信息。
(InteractiveConsole)
>>>

在底部,在三个>>>之后,写入以下内容

>>> from members.models import Member

按 [Enter] 键并写入以下内容以查看空的 Member 表

>>> Member.objects.all()

这应该会给你一个空的 QuerySet 对象,如下所示

<QuerySet []>

QuerySet 是数据库中数据的集合。

Django QuerySet章节中阅读有关 QuerySets 的更多信息。

通过执行以下两行代码,向表中添加一条记录

>>> member = Member(firstname='Emil', lastname='Refsnes')
>>> member.save()

执行以下命令以查看 Member 表是否添加了成员

>>> Member.objects.all().values()

希望结果如下所示

<QuerySet [{'id': 1, 'firstname': 'Emil', 'lastname': 'Refsnes'}]>

添加多条记录

您可以通过创建Member对象的列表,并在每个条目上执行.save()来添加多条记录

>>> member1 = Member(firstname='Tobias', lastname='Refsnes')
>>> member2 = Member(firstname='Linus', lastname='Refsnes')
>>> member3 = Member(firstname='Lene', lastname='Refsnes')
>>> member4 = Member(firstname='Stale', lastname='Refsnes')
>>> member5 = Member(firstname='Jane', lastname='Doe')
>>> members_list = [member1, member2, member3, member4, member5]
>>> for x in members_list
>>>   x.save()

现在 Member 表中有 6 个成员

>>> Member.objects.all().values()
<QuerySet [{'id': 1, 'firstname': 'Emil', 'lastname': 'Refsnes'},
{'id': 2, 'firstname': 'Tobias', 'lastname': 'Refsnes'},
{'id': 3, 'firstname': 'Linus', 'lastname': 'Refsnes'},
{'id': 4, 'firstname': 'Lene', 'lastname': 'Refsnes'},
{'id': 5, 'firstname': 'Stale', 'lastname': 'Refsnes'},
{'id': 6, 'firstname': 'Jane', 'lastname': 'Doe'}]>


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.