Django数据模型增删改查

先导入自己的数据模型
from .models import UserMessage

1
2
3
4
5
6
user_message = UserMessage()
user_message.name = 'bob'
user_message.email = 'test@qq.com'
user_message.address = 'guangzhou'
user_message.message = 'sth.'
user_message.save()

结果:

1
2
3
4
5
6
7
MySQL [opencourse]> select * from message_usermessage;
+----+------+-------------+-----------+---------+
| id | name | email | address | message |
+----+------+-------------+-----------+---------+
| 1 | bob | test@qq.com | guangzhou | sth. |
+----+------+-------------+-----------+---------+

删除的话,调用继承过来的delete()方法即可。
下面删除ID为1的结果

1
2
3
4
5
    user_message = UserMessage.objects.filter(id=1)
# user_message = UserMessage.objects.all()
# user_message.delete()
for message in user_message:
message.delete()

可以直接user_message.delete()所有符合结果的都删除,或者遍历删除,看情况选择使用。

1
2
for message in user_message:
message.delete()

两种方法

1
2
user_message = UserMessage.objects.filter(id=1)
user_message.update(address='shenzhen')

或者

1
2
3
user_message = UserMessage.objects.get(id=1)
user_message.address = 'nanjing'
user_message.save()

结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
第一种方法
MySQL [opencourse]> select * from message_usermessage;
+----+------+-------------+----------+---------+
| id | name | email | address | message |
+----+------+-------------+----------+---------+
| 1 | bob | test@qq.com | shenzhen | sth. |
+----+------+-------------+----------+---------+
1 row in set (0.00 sec)
第二种方法结果
MySQL [opencourse]> select * from message_usermessage;
+----+------+-------------+---------+---------+
| id | name | email | address | message |
+----+------+-------------+---------+---------+
| 1 | bob | test@qq.com | nanjing | sth. |
+----+------+-------------+---------+---------+
1 row in set (0.00 sec)


查询

查询方法还是灵活多变的。filter和get区别
简单来说get的如果多于两条数据,或者没有数据就会报错,它返回对象形式。而filter会返回数组形式。

1
2
3
4
5
UserMessage.objects.all()
UserMessage.objects.all().values('name') # 只取user列
UserMessage.objects.all().values_list('id', 'name') # 取出id和name列
UserMessage.objects.get(id=1)
UserMessage.objects.filter(name='bob')

参考资料

Django-Model操作数据库(增删改查、连表结构)

关注公众号 尹安灿