WED.
Django 数据操作及创建表关系
增
from app import modles
方式一
res = modles. User. objcets. create( username= username, password= password)
print ( res. username, res. password)
方式二
user_obj = modles. User( username= username, password= password)
user_obj. save( )
查
res = models. User. objects. filter ( username= username)
"""
返回值可以看做是列表套数据对象的格式
支持索引取值、切片操作,但不吃负数索引
推荐使用 .first() 方法
res = models.User.objects.filter(username=username).first()
"""
filter 括号内可携带多个参数
参数与参数之间默认是 and 关系
相当于 MySQL 中的 where
数据的查改删
def user_list ( request) :
user_queryset = models. User. objects. all ( )
return render( request, 'user_list.html' , locals ( ) )
- 点击编辑按钮后向后端发送编辑数据的请求
'''
如何获取用户想要编辑的数据的信息?
- 将用户点击的编辑按钮所在的信息发送给后端
- 利用 url '?' 后面可携带参数的格式
'''
{ % for foo in user_queryset % }
< tr>
< td> { { foo. id } } < / td>
< td> { { foo. username } } < / td>
< td> { { foo. password } } < / td>
< td> { { foo. age } } < / td>
< td> { { foo. deposit } } < / td>
< td>
< a href= "/edit/? user_id={{ foo.id }}" class = "btn btn-primary btn-group-sm" > Edit< / a>
< a href= "" class = "btn btn-danger btn-group-sm" > Delete< / a>
< / td>
< / tr>
{ % endfor % }
"""
删除有2种方式:
1、物理删除
2、软删除
"""
delete from user where id = del_id
models. User. objects. filter ( id = del_id) . delete( )
models. User. objects. filter ( id = del_id) . update( is_delete= True )
ORM创建表关系
"""
创建表关系,先创建每张表的基础字段,除了关系字段之外的字段先写好
"""
class Book ( models. Model) :
title = models. CharField( max_length= 32 )
price = models. DecimalField( max_digits= 8 , decimal_places= 2 )
"""
外键关系:
ForeignKey
OneToOneField
自动帮你加上_id,你自己就不要加了
"""
publish = models. ForeignKey( to= 'Publish' )
authors = models. ManyToManyField( to= 'Author' )
"""
authors是一个虚拟字段,不会创建authors字段
"""
class Publish ( models. Model) :
title = models. CharField( max_length= 32 )
addr = models. CharField( max_length= 32 )
class Author ( models. Model) :
name = models. CharField( max_length= 32 )
detail = models. OneToOneField( to= 'AuthorDetail' )
class AuthorDetail ( models. Model) :
phone = models. CharField( max_length= 32 )
email = models. EmailField( )
"" "
一对多创建关系:publish = models. ForeignKey( to= 'Publish' )
多对多: authors = models. ManyToManyField( to= 'Author' )
一对一:detail = models. OneToOneField( to= 'AuthorDetail' )
""