Django-2
Django2
一,基础,配置mysql
(1)添加mysql
DATABASES={
#'default':{
#'ENGINE':'django.db.backends.sqlite3',
#'NAME':os.path.join(BASE_DIR,'db.sqlite3'),
#}
'default':{
'ENGINE':'django.db.backends.mysql',
'USER':'root',
'PASSWORD':'Huada12#$',
'NAME':'django2',
'PORT':3306,
'HOST':'192.168.245.128',
'OPTIONS':{
'init_command':'SETdefault_storage_engine=INNODB',
},
},
}
报错:需要安装mysqlclient
#pip install mysqlclient
(2)#同步数据
#python manage.py migrate
(venv) D:\PycharmProjects\django2>python manage.py showmigrations
admin
[ ] 0001_initial
[ ] 0002_logentry_remove_auto_add
[ ] 0003_logentry_add_action_flag_choices
auth
[ ] 0001_initial
[ ] 0002_alter_permission_name_max_length
[ ] 0003_alter_user_email_max_length
[ ] 0004_alter_user_username_opts
[ ] 0005_alter_user_last_login_null
[ ] 0006_require_contenttypes_0002
[ ] 0007_alter_validators_add_error_messages
[ ] 0008_alter_user_username_max_length
[ ] 0009_alter_user_last_name_max_length
[ ] 0010_alter_group_name_max_length
[ ] 0011_update_proxy_permissions
contenttypes
[ ] 0001_initial
[ ] 0002_remove_content_type_name
dashboard
(no migrations)
sessions
[ ] 0001_initial
怎样查看
#
sessions
[ ] 0001_initial
(venv) D:\PycharmProjects\django2>python manage.py sqlmigrate sessions 0001
BEGIN;
--
-- Create model Session
--
CREATE TABLE `django_session` (`session_key` varchar(40) NOT NULL PRIMARY KEY, `session_data` longtext NOT NULL, `expire_date` dat
etime(6) NOT NULL);
CREATE INDEX `django_session_expire_date_a5c62663` ON `django_session` (`expire_date`);
COMMIT;
#
(3)迁移文件到数据库
#
(venv) D:\PycharmProjects\django2>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying sessions.0001_initial... OK
##
(venv) D:\PycharmProjects\django2>python manage.py dbshell
CommandError: You appear not to have the 'mysql' program installed or on your path.
(venv) D:\PycharmProjects\django2>python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> exit()
(4)#导入user类,创建用户
(venv) D:\PycharmProjects\django2>python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> User.objects.create_user('weizitianming','weizi@163.com','123456')
<User: weizitianming>
>>>
(5)创建超级用户admin
(venv) D:\PycharmProjects\django2>python manage.py createsuperuser
(6)修改密码
(venv) D:\PycharmProjects\django2>python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> u = User.objects.get(username='weizitianming')
>>> u
<User: weizitianming>
>>> u.set_password('654321')
>>> u.save()
>>> exit()
(venv) D:\PycharmProjects\django2>
二、GET、POST
GET:
1,返回所有的用户列表 /users/
2,返回指定用户的信息 /users/12/
POST
1,修改用户信息 /users/12/
body:{
username:"xiaoming"
}
PUT
1, 创建一个用户 /users/
{}
DELETE
1, 删除一个用户
三、
User ---》 1000
10
select * from user limit 0,10 第1页
select * from user limit 11,20 第2页
select * from user limit 21,30 第3页
User.objects.all()[0:10] 第1页
User.objects.all()[10:20] 第2页
User.objects.all()[20:30] 第2页
1,批量创建用户:
>>> python manage.py shell
>>>from django.contrib.auth.models import User
>>>username='weizitianming'
>>>for I in range(1000):
name = '{}_{}'.format(username,i)
User.objects.create_user(name, '{}.@163.com'.format(username),'123456')
<User: weizitianming_0>
<User: weizitianming_1>
<User: weizitianming_2>
<User: weizitianming_3>
<User: weizitianming_4>
<User: weizitianming_5>
<User: weizitianming_6>
<User: weizitianming_7>
<User: weizitianming_8>
2,查询所有数据:User.objects.all()
<User: weizitianming_997>
<User: weizitianming_998>
<User: weizitianming_999>
>>> User.objects.all()
<QuerySet [<User: weizitianming>, <User: weizitianming_0>, <User: weizitianming_1>, <User: weizitianming_2>, <User: weizitianming_
3>, <User: weizitianming_4>, <User: weizitianming_5>, <User: weizitianming_6>, <User: weizitianming_7>, <User: weizitianming_8>, <
User: weizitianming_9>, <User: weizitianming_10>, <User: weizitianming_11>, <User: weizitianming_12>, <User: weizitianming_13>, <U
ser: weizitianming_14>, <User: weizitianming_15>, <User: weizitianming_16>, <User: weizitianming_17>, <User: weizitianming_18>, '.
..(remaining elements truncated)...']>
>>>
3,查询前10条数据
>>> User.objects.all()[:10]
<QuerySet [<User: weizitianming>, <User: weizitianming_0>, <User: weizitianming_1>, <User: weizitianming_2>, <User: weizitianming_
3>, <User: weizitianming_4>, <User: weizitianming_5>, <User: weizitianming_6>, <User: weizitianming_7>, <User: weizitianming_8>]>
>>> queryset.values()
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'queryset' is not defined
>>> queryset = User.objects.all()[:10]
>>> queryset.values()
<QuerySet [{'id': 1, 'password': 'pbkdf2_sha256$150000$Appx9kEcXmwq$hDzz1VX4MXu6M4ttTIgfaNdXz/2YIgIku19ySeEXtjE=', 'last_login': d
atetime.datetime(2019, 7, 14, 7, 18, 7, 72348, tzinfo=<UTC>), 'is_superuser': False, 'username': 'weizitianming', 'first_name': ''
, 'last_name': '', 'email': 'weizi@163.com', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2019, 7, 14, 4
, 7, 48, 552477, tzinfo=<UTC>)}, {'id': 2, 'password': 'pbkdf2_sha256$150000$o6h9oIwfsjLA$Md9ld8MDvpk8PsHsJsUaKOA06H8bg4KovcSlcqyq
u44=', 'last_login': None, 'is_superuser': False, 'username': 'weizitianming_0', 'first_name': '', 'last_name': '', 'email': '()@1
63.com', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2019, 7, 14, 23, 29, 46, 359455, tzinfo=<UTC>)}, {
'id': 3, 'password': 'pbkdf2_sha256$150000$STqeOGUFBywC$uzvO8eNDahweRPnkvc8y/XD2PTnD0XHxEVRgsGZfMhY=', 'last_login': None, 'is_sup
eruser': False, 'username': 'weizitianming_1', 'first_name': '', 'last_name': '', 'email': '()@163.com', 'is_staff': False, 'is_ac
tive': True, 'date_joined': datetime.datetime(2019, 7, 14, 23, 29, 46, 724075, tzinfo=<UTC>)}, {'id': 4, 'password': 'pbkdf2_sha25
6$150000$PB3xSjKQnfo7$yJ34nisYjMqJe0u/GCNx5pNAvjNUCA9QbyeG8K+/6Ms=', 'last_login': None, 'is_superuser': False, 'username': 'weizi
tianming_2', 'first_name': '', 'last_name': '', 'email': '()@163.com', 'is_staff': False, 'is_active': True, 'date_joined': dateti
me.datetime(2019, 7, 14, 23, 29, 46, 958089, tzinfo=<UTC>)}, {'id': 5, 'password': 'pbkdf2_sha256$150000$AF5GqmmUe5jg$lLFROaAmzi3R
dfxLvs0JGkXB69LauxINsrBUmthimU4=', 'last_login': None, 'is_superuser': False, 'username': 'weizitianming_3', 'first_name': '', 'la
st_name': '', 'email': '()@163.com', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2019, 7, 14, 23, 29, 4
7, 190701, tzinfo=<UTC>)}, {'id': 6, 'password': 'pbkdf2_sha256$150000$yHlHkLbHzcEg$66UqxFVo7np/9bUyiK4dzm2mpj6SJoOTKe5nxSct99s=',
'last_login': None, 'is_superuser': False, 'username': 'weizitianming_4', 'first_name': '', 'last_name': '', 'email': '()@163.com
', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2019, 7, 14, 23, 29, 47, 423714, tzinfo=<UTC>)}, {'id':
7, 'password': 'pbkdf2_sha256$150000$QrbKqdAQje1V$gMUepbUnkvZ0TZZLtnr+1HJDRAGFhRVa7hRszhW+KTg=', 'last_login': None, 'is_superuser
': False, 'username': 'weizitianming_5', 'first_name': '', 'last_name': '', 'email': '()@163.com', 'is_staff': False, 'is_active':
True, 'date_joined': datetime.datetime(2019, 7, 14, 23, 29, 47, 654723, tzinfo=<UTC>)}, {'id': 8, 'password': 'pbkdf2_sha256$1500
00$KtqYIcqWMDzR$1fWS7Nc1ohsAF/HG+LvFWFp1NUQBMYkmwJXW11GsIp0=', 'last_login': None, 'is_superuser': False, 'username': 'weizitianmi
ng_6', 'first_name': '', 'last_name': '', 'email': '()@163.com', 'is_staff': False, 'is_active': True, 'date_joined': datetime.dat
etime(2019, 7, 14, 23, 29, 47, 885736, tzinfo=<UTC>)}, {'id': 9, 'password': 'pbkdf2_sha256$150000$tO2d5l2Z6vK9$Ln1w9ZrGl6DH7DqO35
K9qGt2FrBpwSEbEl1KTgIOddQ=', 'last_login': None, 'is_superuser': False, 'username': 'weizitianming_7', 'first_name': '', 'last_nam
e': '', 'email': '()@163.com', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2019, 7, 14, 23, 29, 48, 117
749, tzinfo=<UTC>)}, {'id': 10, 'password': 'pbkdf2_sha256$150000$SqrXS5nF4W0v$BuJPVfZ/xxo1E4Z766H1UOCgr58CbU78LYgPjm8lr4A=', 'las
t_login': None, 'is_superuser': False, 'username': 'weizitianming_8', 'first_name': '', 'last_name': '', 'email': '()@163.com', 'i
s_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2019, 7, 14, 23, 29, 48, 350262, tzinfo=<UTC>)}]>
>>>
4,取部分数据
>>> queryset.values('username','email')
<QuerySet [{'username': 'weizitianming_999', 'email': '()@163.com'}, {'username': 'weizitianming_1000', 'email': 'weizitianming_10
00@163.com'}, {'username': 'weizitianming_1001', 'email': 'weizitianming_1001@163.com'}, {'username': 'weizitianming_1002', 'email
': 'weizitianming_1002@163.com'}, {'username': 'weizitianming_1003', 'email': 'weizitianming_1003@163.com'}, {'username': 'weiziti
anming_1004', 'email': 'weizitianming_1004@163.com'}, {'username': 'weizitianming_1005', 'email': 'weizitianming_1005@163.com'}, {
'username': 'weizitianming_1006', 'email': 'weizitianming_1006@163.com'}, {'username': 'weizitianming_1007', 'email': 'weizitianmi
ng_1007@163.com'}, {'username': 'weizitianming_1008', 'email': 'weizitianming_1008@163.com'}, {'username': 'weizitianming_1009', '
email': 'weizitianming_1009@163.com'}, {'username': 'weizitianming_1010', 'email': 'weizitianming_1010@163.com'}, {'username': 'we
izitianming_1011', 'email': 'weizitianming_1011@163.com'}, {'username': 'weizitianming_1012', 'email': 'weizitianming_1012@163.com
'}, {'username': 'weizitianming_1013', 'email': 'weizitianming_1013@163.com'}, {'username': 'weizitianming_1014', 'email': 'weizit
ianming_1014@163.com'}, {'username': 'weizitianming_1015', 'email': 'weizitianming_1015@163.com'}, {'username': 'weizitianming_101
6', 'email': 'weizitianming_1016@163.com'}, {'username': 'weizitianming_1017', 'email': 'weizitianming_1017@163.com'}, {'username'
: 'weizitianming_1018', 'email': 'weizitianming_1018@163.com'}]>
>>>
>>> list(queryset.values('username','email'))
[{'username': 'weizitianming_999', 'email': '()@163.com'}, {'username': 'weizitianming_1000', 'email': 'weizitianming_1000@163.com
'}, {'username': 'weizitianming_1001', 'email': 'weizitianming_1001@163.com'}, {'username': 'weizitianming_1002', 'email': 'weizit
ianming_1002@163.com'}, {'username': 'weizitianming_1003', 'email': 'weizitianming_1003@163.com'}, {'username': 'weizitianming_100
4', 'email': 'weizitianming_1004@163.com'}, {'username': 'weizitianming_1005', 'email': 'weizitianming_1005@163.com'}, {'username'
: 'weizitianming_1006', 'email': 'weizitianming_1006@163.com'}, {'username': 'weizitianming_1007', 'email': 'weizitianming_1007@16
3.com'}, {'username': 'weizitianming_1008', 'email': 'weizitianming_1008@163.com'}, {'username': 'weizitianming_1009', 'email': 'w
eizitianming_1009@163.com'}, {'username': 'weizitianming_1010', 'email': 'weizitianming_1010@163.com'}, {'username': 'weizitianmin
g_1011', 'email': 'weizitianming_1011@163.com'}, {'username': 'weizitianming_1012', 'email': 'weizitianming_1012@163.com'}, {'user
name': 'weizitianming_1013', 'email': 'weizitianming_1013@163.com'}, {'username': 'weizitianming_1014', 'email': 'weizitianming_10
14@163.com'}, {'username': 'weizitianming_1015', 'email': 'weizitianming_1015@163.com'}, {'username': 'weizitianming_1016', 'email
': 'weizitianming_1016@163.com'}, {'username': 'weizitianming_1017', 'email': 'weizitianming_1017@163.com'}, {'username': 'weiziti
anming_1018', 'email': 'weizitianming_1018@163.com'}]
>>>
三,数据分页
1,分析
问题1 /users/?page=1
Start = (page-1) *10
End = page * 10
Start = end - 10
问题2 /users/10/
id , username, email
解析:
1, 拿到page =》 str
2,获取数据:User.objects.all()
3,对数据处理进行,分页;
根据page,计算切片的start与end
queryset = User.objects.all()[:10]
4, 转JSON
Ret = list(queryset.values('id','username','email'))
5,HttpResponse
2,视图
classMyView(View):
defget(self,request,*args,**kwargs):
try:
page=int(request.GET.get("page",1))
except:
page=1
end=page*10
start=end-10
queryset=User.objects.all()[start:end]
data=list(queryset.values('id','username','email'))
returnJsonResponse(data,safe=False)
3,分析
一共有多少条记录;
一共可以分多少页;
是否有上一页,上一页的页码
是否有下一页,下一页的页码
首页
尾页
https://devdocs.io/
(venv) D:\PycharmProjects\django2> python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC
Type "help", "copyright", "credits" or "license" for more in
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> queryset = User.objects.all()
>>> from django.core.paginator import Paginator
>>> paginator = Paginator(queryset,10)
<string>:1: UnorderedObjectListWarning: Pagination may yield inconsistent results with an
unordered object_list: <class 'django.contrib.auth.models.User'> QuerySet.
>>> paginator.count
1101
>>> pgainator.num_pages
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'pgainator' is not defined
>>> paginator.num_pages
111
>>> paginator.page_range
range(1, 112)
>>>
>>> page = paginator.page(10)
>>> page.object_list
<QuerySet [<User: weizitianming_89>, <User: weizitianming_90>, <User: weizitianming_91>,
<User: weizitianming_92>, <User: weizitianming_93>, <User: weizitianming_94>, <User: weiz
itianming_95>, <User: weizitianming_96>, <User: weizitianming_97>, <User: weizitianming_9
8>]>
>>> page.number
10
>>> page.has_next()
True
>>> page.next_page_number()
11
>>> page = paginator.age(1)
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Paginator' object has no attribute 'age'
>>> page = paginator.page(1)
>>> page.previous_page_number()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "D:\PycharmProjects\django2\venv\lib\site-packages\django\core\paginator.py", line
174, in previous_page_number
return self.paginator.validate_number(self.number - 1)
File "D:\PycharmProjects\django2\venv\lib\site-packages\django\core\paginator.py", line
47, in validate_number
raise EmptyPage(_('That page number is less than 1'))
django.core.paginator.EmptyPage: That page number is less than 1
>>> page.has_previous
<bound method Page.has_previous of <Page 1 of 111>>
>>> page.has_previous()
False
>>>
Create table user (
id primary key,
username char(20) not null,
)
四,同步到数据库
1,同步app的dashboard的数据库
(venv) D:\PycharmProjects\django2>python manage.py makemigrations dashboard
error 日志
Migrations for 'dashboard':
dashboard\migrations\0001_initial.py
- Create model Idc
(venv) D:\PycharmProjects\django2>python manage.py showmigrations
error 日志
admin
[X] 0001_initial
[X] 0002_logentry_remove_auto_add
[X] 0003_logentry_add_action_flag_choices
auth
[X] 0001_initial
[X] 0002_alter_permission_name_max_length
[X] 0003_alter_user_email_max_length
[X] 0004_alter_user_username_opts
[X] 0005_alter_user_last_login_null
[X] 0006_require_contenttypes_0002
[X] 0007_alter_validators_add_error_messages
[X] 0008_alter_user_username_max_length
[X] 0009_alter_user_last_name_max_length
[X] 0010_alter_group_name_max_length
[X] 0011_update_proxy_permissions
contenttypes
[X] 0001_initial
[X] 0002_remove_content_type_name
dashboard
[ ] 0001_initial
sessions
[X] 0001_initial
2,查看同步的app的数据库
(venv) D:\PycharmProjects\django2>python manage.py sqlmigrate dashboard 0001_initial
error 日志
BEGIN;
--
-- Create model Idc
--
CREATE TABLE `dashboard_idc` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(32) NOT NULL, `address` varchar(200
) NOT NULL, `phone` varchar(15) NOT NULL, `email` varchar(254) NOT NULL, `letter` varchar(5) NOT NULL);
COMMIT;
(venv) D:\PycharmProjects\django2>
3,同步所有的数据库,
(venv) D:\PycharmProjects\django2>python manage.py migrate
error 日志
Operations to perform:
Apply all migrations: admin, auth, contenttypes, dashboard, sessions
Running migrations:
Applying dashboard.0001_initial... OK
(venv) D:\PycharmProjects\django2>python manage.py migrate --help
usage: manage.py migrate [-h] [--noinput] [--database DATABASE] [--fake]
[--fake-initial] [--plan] [--run-syncdb] [--version]
[-v {0,1,2,3}] [--settings SETTINGS]
[--pythonpath PYTHONPATH] [--traceback] [--no-color]
[--force-color]
[app_label] [migration_name]
Updates database schema. Manages both apps with migrations and those without.
positional arguments:
app_label App label of an application to synchronize the state.
migration_name Database state will be brought to the state after that
migration. Use the name "zero" to unapply all
migrations.
optional arguments:
-h, --help show this help message and exit
--noinput, --no-input
Tells Django to NOT prompt the user for input of any
kind.
--database DATABASE Nominates a database to synchronize. Defaults to the
"default" database.
--fake Mark migrations as run without actually running them.
--fake-initial Detect if tables already exist and fake-apply initial
migrations if so. Make sure that the current database
schema matches your initial migration before using
this flag. Django will only check for an existing
table name.
--plan Shows a list of the migration actions that will be
performed.
--run-syncdb Creates tables for apps without migrations.
--version show program's version number and exit
-v {0,1,2,3}, --verbosity {0,1,2,3}
Verbosity level; 0=minimal output, 1=normal output,
2=verbose output, 3=very verbose output
--settings SETTINGS The Python path to a settings module, e.g.
"myproject.settings.main". If this isn't provided, the
DJANGO_SETTINGS_MODULE environment variable will be
used.
--pythonpath PYTHONPATH
A directory to add to the Python path, e.g.
"/home/djangoprojects/myproject".
--traceback Raise on CommandError exceptions
--no-color Don't colorize the command output.
--force-color Force colorization of the command output.
4,同步app的数据库
(venv) D:\PycharmProjects\django2>python manage.py migrate dashboard
5,对app的表结构更新到最新:
#
(venv) D:\PycharmProjects\django2>python manage.py migrate dashboard --fake
error 日志
Operations to perform:
Apply all migrations: dashboard
Running migrations:
No migrations to apply.
6,同步django的数据库,
(venv) D:\PycharmProjects\django2>python manage.py migrate --fake
error 日志
Operations to perform:
Apply all migrations: admin, auth, contenttypes, dashboard, sessions
Running migrations:
No migrations to apply.
7,迁移失败的处理方法
1,models
2,migrations
3,mysql table
4,django_migrations
四个地方只要有一个错误,其他的都会有问题;
解决方法:1,先把models.py 里的注释掉
2,删除migrations下面的文件
3,同步
#python manage.py migrate dashboard --fake
4,把models.py 里的注释取消;
#python manage.py makemigrations dashboard
#
#python manage.py migrate dashboard
#
#python manage.py showmigrations
#python manage.py migrate dashboard
#
##########################
(venv) D:\PycharmProjects\django2>python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> ?User.objects.create
File "<console>", line 1
?User.objects.create
^
SyntaxError: invalid syntax
>>> ?User.objects.create
File "<console>", line 1
?User.objects.create
^
SyntaxError: invalid syntax
>>> ?User.objects.create_user
File "<console>", line 1
?User.objects.create_user
^
SyntaxError: invalid syntax
>>> ? User.objects.create_user
File "<console>", line 1
? User.objects.create_user
^
SyntaxError: invalid syntax
第1种方式创建对象
>>> User.objects.create_user(username="weizis1", email="weizi@163.com",password="123456")
<User: weizis1>
>>>
第2种方式创建对象(实例化对象,赋值)
>>> user = User()
>>> user.username = "weizis2"
>>> user.password = "weizis2@163.com"
>>> user.email = "weizis2@163.com"
>>> user.save()
>>>
在数据库中标auth_user可以看到新增的两条记录:
1103 pbkdf2_sha256$150000$DeddbcUzbktn$v4euvCFcSrbVkRpRjda+Loercp4LdydPz1WyqrjPTm4= 0 weizis1 "" "" weizi@163.com 0 1 2019-07-18 23:03:02.046747000
1104 weizis2@163.com 0 weizis2 "" "" weizis2@163.com 0 1 2019-07-18 23:05:38.957453000
>>> from dashboard.models import Idc
>>> idc = Idc()
>>> idc.name = "子镇机房"
>>> idc.letter = "zz"
>>> idc.email = "weizizhen@163.com"
>>> idc.addresss = "山西微子镇机房"
>>> idc.phone = "123456789"
>>> idc.save()
数据库查看是否有记录;
1 zizhenjifang shanxizizhen 123456789 zizhen@163.com zz
报错:
django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xE5\\xAD\\x90\\xE9\\x95\\x87...' for column 'name' at row 1")
(venv) D:\PycharmProjects\django2>python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> queryset = User.objects.all()
>>> queryset
<QuerySet [<User: weizitianming>, <User: weizitianming_0>, <User: weizitianming_1>, <User: weizitianming_2>, <User: weizitianming_
3>, <User: weizitianming_4>, <User: weizitianming_5>, <User: weizitianming_6>, <User: weizitianming_7>, <User: weizitianming_8>, <
User: weizitianming_9>, <User: weizitianming_10>, <User: weizitianming_11>, <User: weizitianming_12>, <User: weizitianming_13>, <U
ser: weizitianming_14>, <User: weizitianming_15>, <User: weizitianming_16>, <User: weizitianming_17>, <User: weizitianming_18>, '.
..(remaining elements truncated)...']>
>>> queryset.count()
1103
>>> queryset.filter(username="weizitianming")
<QuerySet [<User: weizitianming>]>
>>> queryset.filter(username__startswith="weizi")
<QuerySet [<User: weizitianming>, <User: weizitianming_0>, <User: weizitianming_1>, <User: weizitianming_2>, <User: weizitianming_
3>, <User: weizitianming_4>, <User: weizitianming_5>, <User: weizitianming_6>, <User: weizitianming_7>, <User: weizitianming_8>, <
User: weizitianming_9>, <User: weizitianming_10>, <User: weizitianming_11>, <User: weizitianming_12>, <User: weizitianming_13>, <U
ser: weizitianming_14>, <User: weizitianming_15>, <User: weizitianming_16>, <User: weizitianming_17>, <User: weizitianming_18>, '.
..(remaining elements truncated)...']>
>>>
以什么为开头的查询
>>> q1 = queryset.filter(username__startswith="weizi")
>>> print(q1.query)
SELECT `auth_user`.`id`, `auth_user`.`password`, `auth_user`.`last_login`, `auth_user`.`is_superuser`, `auth_user`.`username`, `au
th_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.
`date_joined` FROM `auth_user` WHERE `auth_user`.`username` LIKE BINARY weizi%
>>>
QuerySet就是管理器
>>> q1
<QuerySet [<User: weizitianming>, <User: weizitianming_0>, <User: weizitianming_1>, <User: weizitianming_2>, <User: weizitianming_
3>, <User: weizitianming_4>, <User: weizitianming_5>, <User: weizitianming_6>, <User: weizitianming_7>, <User: weizitianming_8>, <
User: weizitianming_9>, <User: weizitianming_10>, <User: weizitianming_11>, <User: weizitianming_12>, <User: weizitianming_13>, <U
ser: weizitianming_14>, <User: weizitianming_15>, <User: weizitianming_16>, <User: weizitianming_17>, <User: weizitianming_18>, '.
..(remaining elements truncated)...']>
>>>
(venv) D:\PycharmProjects\django2>python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> User.objects.all()
<QuerySet [<User: weizitianming>, <User: weizitianming_0>, <User: weizitianming_1>, <User: weizitianming_2>, <User: weizitianming_
3>, <User: weizitianming_4>, <User: weizitianming_5>, <User: weizitianming_6>, <User: weizitianming_7>, <User: weizitianming_8>, <
User: weizitianming_9>, <User: weizitianming_10>, <User: weizitianming_11>, <User: weizitianming_12>, <User: weizitianming_13>, <U
ser: weizitianming_14>, <User: weizitianming_15>, <User: weizitianming_16>, <User: weizitianming_17>, <User: weizitianming_18>, '.
..(remaining elements truncated)...']>
>>> queryset = User.objects.all()
>>> queryset.query
<django.db.models.sql.query.Query object at 0x0000000003E33668>
>>> print(queryset.query)
SELECT `auth_user`.`id`, `auth_user`.`password`, `auth_user`.`last_login`, `auth_user`.`is_superuser`, `auth_user`.`username`, `au
th_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.
`date_joined` FROM `auth_user`
>>> q1 = queryset.filter(username__startswith="weizi")
>>> print(q1.query)
SELECT `auth_user`.`id`, `auth_user`.`password`, `auth_user`.`last_login`, `auth_user`.`is_superuser`, `auth_user`.`username`, `au
th_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.
`date_joined` FROM `auth_user` WHERE `auth_user`.`username` LIKE BINARY weizi%
>>> list(q1)
[<User: weizitianming>, <User: weizitianming_0>, <User: weizitianming_1>, <User: weizitianming_2>, <User: weizitianming_3>]
>>>
>>> qc = queryset.count()
>>> qc
1103
>>>
filter返回一个查询集
>>> User.objects.filter(username="weizis1")
<QuerySet [<User: weizis1>]>
get不满足条件报异常
>>> User.objects.get(username="weizis1")
<User: weizis1>
>>>
>>> User.objects.get(username="weizis11")
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "D:\PycharmProjects\django2\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\PycharmProjects\django2\venv\lib\site-packages\django\db\models\query.py", line 408, in get
self.model._meta.object_name
django.contrib.auth.models.User.DoesNotExist: User matching query does not exist.
限制结果集查询
>>> queryset = User.objects.all()[:10]
>>> print(queryset)
<QuerySet [<User: weizitianming>, <User: weizitianming_0>, <User: weizitianming_1>, <User: weizitianming_2>, <User: weizitianming_
3>, <User: weizitianming_4>, <User: weizitianming_5>, <User: weizitianming_6>, <User: weizitianming_7>, <User: weizitianming_8>]>
>>> queryset = User.objects.all()[5:10]
>>> print(queryset)
<QuerySet [<User: weizitianming_4>, <User: weizitianming_5>, <User: weizitianming_6>, <User: weizitianming_7>, <User: weizitianmin
g_8>]>
精准查询
>>> queryset = User.objects.filter(username__exact="weizis1")
打印sql语句
>>> print(queryset.query)
SELECT `auth_user`.`id`, `auth_user`.`password`, `auth_user`.`last_login`, `auth_user`.`is_superuser`, `auth_user`.`username`, `au
th_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.
`date_joined` FROM `auth_user` WHERE `auth_user`.`username` = weizis1
>>>
或者另一种写法
>>> q1 = User.objects.filter(username="weizis1")
>>> print(q1.query)
SELECT `auth_user`.`id`, `auth_user`.`password`, `auth_user`.`last_login`, `auth_user`.`is_superuser`, `auth_user`.`username`, `au
th_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.
`date_joined` FROM `auth_user` WHERE `auth_user`.`username` = weizis1
>>>
正序查询
>>> User.objects.order_by("id")
<QuerySet [<User: weizitianming>, <User: weizitianming_0>, <User: weizitianming_1>, <User: weizitianming_2>, <User: weizitianming_
3>, <User: weizitianming_4>, <User: weizitianming_5>, <User: weizitianming_6>, <User: weizitianming_7>, <User: weizitianming_8>, <
User: weizitianming_9>, <User: weizitianming_10>, <User: weizitianming_11>, <User: weizitianming_12>, <User: weizitianming_13>, <U
ser: weizitianming_14>, <User: weizitianming_15>, <User: weizitianming_16>, <User: weizitianming_17>, <User: weizitianming_18>, '.
..(remaining elements truncated)...']>
倒序查询
>>> User.objects.order_by("-id")
<QuerySet [<User: weizis2>, <User: weizis1>, <User: weizitianming_1099>, <User: weizitianming_1098>, <User: weizitianming_1097>, <
User: weizitianming_1096>, <User: weizitianming_1095>, <User: weizitianming_1094>, <User: weizitianming_1093>, <User: weizitianmin
g_1092>, <User: weizitianming_1091>, <User: weizitianming_1090>, <User: weizitianming_1089>, <User: weizitianming_1088>, <User: we
izitianming_1087>, <User: weizitianming_1086>, <User: weizitianming_1085>, <User: weizitianming_1084>, <User: weizitianming_1083>,
<User: weizitianming_1082>, '...(remaining elements truncated)...']>
>>>
随机查询
>>> User.objects.order_by("?")
<QuerySet [<User: weizitianming_42>, <User: weizitianming_916>, <User: weizitianming_237>, <User: weizitianming_247>, <User: weizi
tianming_1033>, <User: weizitianming_741>, <User: weizitianming_1041>, <User: weizitianming_24>, <User: weizitianming_661>, <User:
weizitianming_965>, <User: weizitianming_905>, <User: weizitianming_265>, <User: weizitianming_1088>, <User: weizitianming_109>,
<User: weizitianming_348>, <User: weizitianming_256>, <User: weizitianming_1085>, <User: weizitianming_901>, <User: weizitianming_
282>, <User: weizitianming_997>, '...(remaining elements truncated)...']>
>>>
values返回一个字典
>>> User.objects.values('id','username','email')
<QuerySet [{'id': 1, 'username': 'weizitianming', 'email': 'weizi@163.com'}, {'id': 2, 'username': 'weizitianming_0', 'email': '()
@163.com'}, {'id': 3, 'username': 'weizitianming_1', 'email': '()@163.com'}, {'id': 4, 'username': 'weizitianming_2', 'email': '()
@163.com'}, {'id': 5, 'username': 'weizitianming_3', 'email': '()@163.com'}, {'id': 6, 'username': 'weizitianming_4', 'email': '()
@163.com'}, {'id': 7, 'username': 'weizitianming_5', 'email': '()@163.com'}, {'id': 8, 'username': 'weizitianming_6', 'email': '()
@163.com'}, {'id': 9, 'username': 'weizitianming_7', 'email': '()@163.com'}, {'id': 10, 'username': 'weizitianming_8', 'email': '(
)@163.com'}, {'id': 11, 'username': 'weizitianming_9', 'email': '()@163.com'}, {'id': 12, 'username': 'weizitianming_10', 'email':
'()@163.com'}, {'id': 13, 'username': 'weizitianming_11', 'email': '()@163.com'}, {'id': 14, 'username': 'weizitianming_12', 'ema
il': '()@163.com'}, {'id': 15, 'username': 'weizitianming_13', 'email': '()@163.com'}, {'id': 16, 'username': 'weizitianming_14',
'email': '()@163.com'}, {'id': 17, 'username': 'weizitianming_15', 'email': '()@163.com'}, {'id': 18, 'username': 'weizitianming_1
6', 'email': '()@163.com'}, {'id': 19, 'username': 'weizitianming_17', 'email': '()@163.com'}, {'id': 20, 'username': 'weizitianmi
ng_18', 'email': '()@163.com'}, '...(remaining elements truncated)...']>
>>>
Values_list返回一个元祖
>>> User.objects.values_list('id','username','email')
<QuerySet [(1, 'weizitianming', 'weizi@163.com'), (2, 'weizitianming_0', '()@163.com'), (3, 'weizitianming_1', '()@163.com'), (4,
'weizitianming_2', '()@163.com'), (5, 'weizitianming_3', '()@163.com'), (6, 'weizitianming_4', '()@163.com'), (7, 'weizitianming_5
', '()@163.com'), (8, 'weizitianming_6', '()@163.com'), (9, 'weizitianming_7', '()@163.com'), (10, 'weizitianming_8', '()@163.com'
), (11, 'weizitianming_9', '()@163.com'), (12, 'weizitianming_10', '()@163.com'), (13, 'weizitianming_11', '()@163.com'), (14, 'we
izitianming_12', '()@163.com'), (15, 'weizitianming_13', '()@163.com'), (16, 'weizitianming_14', '()@163.com'), (17, 'weizitianmin
g_15', '()@163.com'), (18, 'weizitianming_16', '()@163.com'), (19, 'weizitianming_17', '()@163.com'), (20, 'weizitianming_18', '()
@163.com'), '...(remaining elements truncated)...']>
>>>
排除某些字段查询
>>> queryset = User.objects.all().defer("password",'first_name')
>>> print(queryset.query)
SELECT `auth_user`.`id`, `auth_user`.`last_login`, `auth_user`.`is_superuser`, `auth_user`.`username`, `auth_user`.`last_name`, `a
uth_user`.`email`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.`date_joined` FROM `auth_user`
>>>
>>> queryset = User.objects.order_by("id")
>>> print(queryset.query)
SELECT `auth_user`.`id`, `auth_user`.`password`, `auth_user`.`last_login`, `auth_user`.`is_superuser`, `auth_user`.`username`, `au
th_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.
`date_joined` FROM `auth_user` ORDER BY `auth_user`.`id` ASC
>>> queryset
<QuerySet [<User: weizitianming>, <User: weizitianming_0>, <User: weizitianming_1>, <User: weizitianming_2>, <User: weizitianming_
3>, <User: weizitianming_4>, <User: weizitianming_5>, <User: weizitianming_6>, <User: weizitianming_7>, <User: weizitianming_8>, <
User: weizitianming_9>, <User: weizitianming_10>, <User: weizitianming_11>, <User: weizitianming_12>, <User: weizitianming_13>, <U
ser: weizitianming_14>, <User: weizitianming_15>, <User: weizitianming_16>, <User: weizitianming_17>, <User: weizitianming_18>, '.
..(remaining elements truncated)...']>
>>> queryset.values()
<QuerySet [{'id': 1, 'password': 'pbkdf2_sha256$150000$Appx9kEcXmwq$hDzz1VX4MXu6M4ttTIgfaNdXz/2YIgIku19ySeEXtjE=', 'last_login': d
atetime.datetime(2019, 7, 14, 7, 18, 7, 72348, tzinfo=<UTC>), 'is_superuser': False, 'username': 'weizitianming', 'first_name': ''
, 'last_name': '', 'email': 'weizi@163.com', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2019, 7, 14, 4
, 7, 48, 552477, tzinfo=<UTC>)}, {'id': 2, 'password': 'pbkdf2_sha256$150000$o6h9oIwfsjLA$Md9ld8MDvpk8PsHsJsUaKOA06H8bg4KovcSlcqyq
u44=', 'last_login': None, 'is_superuser': False, 'username': 'weizitianming_0',
序列化
>>> data = queryset.values()
>>>list(data)
{'id': 1104,
'password': 'weizis2@163.com', 'last_login': None, 'is_superuser': False, 'username': 'weizis2', 'first_name': '', 'last_name': '
', 'email': 'weizis2@163.com', 'is_staff': False, 'is_active': True, 'date_joined': datetime.datetime(2019, 7, 18, 23, 5, 38, 9574
53, tzinfo=<UTC>)}]
转化为JSON格式
>>> from django.core import serializers
>>> from dashboard.models import Idc
>>>
>>> Idc.objects.all()
<QuerySet [<Idc: Idc object (1)>]>
>>> data = serializers.serialize("json",Idc.objects.all())
>>> data
'[{"model": "dashboard.idc", "pk": 1, "fields": {"name": "zizhenjifang", "address": "shanxizizhen", "phone": "123456789", "email":
"zizhen@163.com", "letter": "zz"}}]'
>>>
>>> queryset
<QuerySet [<User: weizitianming>, <User: weizitianming_0>, <User: weizitianming_1>, <User: weizitianming_2>, <User: weizitianming_
3>, <User: weizitianming_4>, <User: weizitianming_5>, <User: weizitianming_6>, <User: weizitianming_7>, <User: weizitianming_8>, <
User: weizitianming_9>, <User: weizitianming_10>, <User: weizitianming_11>, <User: weizitianming_12>, <User: weizitianming_13>, <U
ser: weizitianming_14>, <User: weizitianming_15>, <User: weizitianming_16>, <User: weizitianming_17>, <User: weizitianming_18>, '.
..(remaining elements truncated)...']>
>>> data = serializers.serialize("json",queryset)
>>>data
{"model": "auth.user", "pk": 1103, "fields": {"password": "pbkdf2_sha256$150000$DeddbcUzbktn$v4euvC
FcSrbVkRpRjda+Loercp4LdydPz1WyqrjPTm4=", "last_login": null, "is_superuser": false, "username": "weizis1", "first_name": "", "last
_name": "", "email": "weizi@163.com", "is_staff": false, "is_active": true, "date_joined": "2019-07-18T23:03:02.046Z", "groups": [
], "user_permissions": []}},
需求:
User
page =1
size = 10
1,查询出所有对象
2,对queryset 进行分页
3,转JSON序列化
多对1或1对多
(venv) D:\PycharmProjects\django2>python manage.py makemigrations dashboard
error 日志
Migrations for 'dashboard':
dashboard\migrations\0002_car_manufacturer.py
- Create model Manufacturer
- Create model Car
(venv) D:\PycharmProjects\django2>python manage.py migrate dashboard
error 日志
Operations to perform:
Apply all migrations: dashboard
Running migrations:
Applying dashboard.0002_car_manufacturer... OK
(venv) D:\PycharmProjects\django2>python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from dashboard.models import Manufacturer
>>> Manufacturer.objects.create(name="吉利")
>>> Manufacturer.objects.create(name="jili")
<Manufacturer: Manufacturer object (1)>
>>> Manufacturer.objects.create(name="baoma")
<Manufacturer: Manufacturer object (2)>
>>> Manufacturer.objects.all()
<QuerySet [<Manufacturer: Manufacturer object (1)>, <Manufacturer: Manufacturer object (2)>]>
>>>
>>> from dashboard.models import Car
>>> car = Car()
>>> car.name = ""
>>> car.name = "yuanjing"
>>> m = Manufacturer.objects.get(name="jili")
>>> m
<Manufacturer: Manufacturer object (1)>
>>> car.name
'yuanjing'
>>> car.manufacturer = m
>>> car.save()
>>> car = Car()
>>> car.name = "dihao"
>>> car.manufacturer = m
>>> car.save()
>>> Car.objects.all()
<QuerySet [<Car: Car object (1)>, <Car: Car object (2)>]>
>>> car
<Car: Car object (2)>
>>>
正向查询
>>> from dashboard.models import Car, Manufacturer
>>> Car.objects.all()
<QuerySet [<Car: yuanjing>, <Car: dihao>]>
>>> car = Car.objects.all()[0]
>>> car
<Car: yuanjing>
>>> car.manufacturer
<Manufacturer: jili>
制造商的名字
>>> car.manufacturer.name
'jili'
>>>
反向查询
>>> Manufacturer.objects.all()
<QuerySet [<Manufacturer: jili>, <Manufacturer: baoma>]>
>>> m = Manufacturer.objects.all()[0]
>>> m
<Manufacturer: jili>
>>> m.car_set
<django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager object at 0x0000000003F836
D8>
>>> m.car_set.all()
<QuerySet [<Car: yuanjing>, <Car: dihao>]>
>>> m.car_set.filter(name="yuanjing")
<QuerySet [<Car: yuanjing>]>
>>> m.car_set.filter(name__contains="jing")
<QuerySet [<Car: yuanjing>]>
>>>
多对一
>>> from dashboard.models import Manufacturer,Car
>>> Manufacturer.objects.all()
<QuerySet [<Manufacturer: jili>, <Manufacturer: baoma>]>
>>> bm = Manufacturer.objects.all()
>>> bm.car_set.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'QuerySet' object has no attribute 'car_set'
>>> bm
>>>bm.car_set = Car.objects.all()
>>>bm.car_set.all()
>>>m = Manufacturer.objects.all()[1]
>>>m = Manufacturer.objects.all()[0]
>>>m.car_set.all()
>>>
#car1.manufacturer = m
#car1.save()
#m.car_set.all()
#car2.manufacturer =m
#car2.save()
#m.car_set.all()
多对多
>>> from django.contrib.auth.models import User, Group
>>> Group.objects.create(name="op")
<Group: op>
>>> Group.objects.create(name="sa")
<Group: sa>
>>> users = User.objects.filter(username__startswith="weizi")
>>> op = Group.objects.get(name__exact="op")
>>> op.user_set
<django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x000000000
3E002B0>
>>>
>>>op.user_set = users
报错
>>> op.user_set.all()
<QuerySet []>
>>>
>>> Group.objects.all()
<QuerySet [<Group: op>, <Group: sa>]>
>>> op.user_set
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'op' is not defined
>>> op
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'op' is not defined
>>> users = User.objects.filter(username__startswith="weizi")
>>> op = Group.objects.get(name__exact="op")
>>> op.user_set
<django.db.models.fields.related_descriptors.create_forward_many_to_many_manag
er.<locals>.ManyRelatedManager object at 0x0000000003E422B0>
>>> op.user_set.add()
>>> op.user_set = users
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "D:\PycharmProjects\django2\venv\lib\site-packages\django\db\models\fie
lds\related_descriptors.py", line 538, in __set__
% self._get_set_deprecation_msg_params(),
TypeError: Direct assignment to the reverse side of a many-to-many set is proh
ibited. Use user_set.set() instead.
>>> op.user_set.all()
<QuerySet []>
>>> users = User.objects.get(username="weizis1")
>>> user1 = User.objects.get(username="weizis1")
>>> user1.groups
<django.db.models.fields.related_descriptors.create_forward_many_to_many_manag
er.<locals>.ManyRelatedManager object at 0x0000000003E422B0>
>>> user1.groups.all()
<QuerySet []>
>>> sa = Group.objects.get(name="sa")
>>> sa.user_set.add(user1)
>>> user1.groups.all()
<QuerySet [<Group: sa>]>
>>> op.user_set.all()
<QuerySet []>
>>> op.user_set.remove(user1)
>>> op.user_set.all()
<QuerySet []>
>>>
Models.py
Class UserProfile(models.Model):
name=models.CharField("中文姓名",max_length=20)
user=models.OneToOneField(User,on_delete=models.CASCADE)
同步数据
(venv) D:\PycharmProjects\django2>python manage.py makemigrations
error 日志
Migrations for 'dashboard':
dashboard\migrations\0003_userprofile.py
- Create model UserProfile
(venv) D:\PycharmProjects\django2>python manage.py migrate
error 日志
Operations to perform:
Apply all migrations: admin, auth, contenttypes, dashboard, sessions
Running migrations:
Applying dashboard.0003_userprofile... OK
(venv) D:\PycharmProjects\django2>python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> from dashboard.models import UserProfile
>>> user = User.objects.get(username="weizis1")
>>> user.userprofile
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "D:\PycharmProjects\django2\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 415, in __get__
self.related.get_accessor_name()
django.contrib.auth.models.User.userprofile.RelatedObjectDoesNotExist: User has no userprofile.
>>> userprofile = UserProfile()
>>> userprofile.name="WEIZI"
>>> userprofile.user = user
>>> userprofile.save()
>>> user.userprofile
<UserProfile: UserProfile object (1)>
>>> user.userprofile.name
'WEIZI'
>>> user.username
'weizis1'
>>>
>>> userprofile.user
<User: weizis1>
>>> userprofile.user.username
'weizis1'
>>>
关联查询
>>> User.objects.filter(groups__name__exact="op")
<QuerySet []>
>>> User.objects.filter(groups__name__exact="sa")
<QuerySet [<User: weizis1>]>
>>> queryset = User.objects.filter(groups__name__exact="sa")
>>> print(queryset.query)
SELECT `auth_user`.`id`, `auth_user`.`password`, `auth_user`.`last_login`, `auth_user`.`is_superuser`, `auth_user`.`username`, `au
th_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.
`date_joined` FROM `auth_user` INNER JOIN `auth_user_groups` ON (`auth_user`.`id` = `auth_user_groups`.`user_id`) INNER JOIN `auth
_group` ON (`auth_user_groups`.`group_id` = `auth_group`.`id`) WHERE `auth_group`.`name` = sa
>>>