Django Model对象

2022-08-10 10:35:18

1、定义model对象

from django.db import models

# Create your models here.
from django.db import models
from django.contrib.auth.models import User


class BaseModel(models.Model):
    """"
    post应用中的Model的基类
    """
    class Meta:
        abstract = True
        ordering = ['-create_time']
    create_time = models.DateTimeField(auto_now_add=True,
                                       help_text=u'创建时间')
    last_modfied = models.DateTimeField(auto_now=True,
                                        help_text=u'修改时间')
    def __str__(self):
        raise NotImplementedError


class Topic(BaseModel):
    title = models.CharField(max_length=255, unique=True, help_text='话题标题')
    content = models.TextField(help_text='话题内容')
    is_online = models.BooleanField(default=True, help_text='话题是否在线')
    user = models.ForeignKey(to=User, to_field='id', on_delete=models.CASCADE,
                             help_text='关联用户表')
    def __str__(self):
        return '%d : %d' % (self.id, self.title[0:20])


class Comment(BaseModel):
    content =models.CharField(max_length=255, help_text='话题评论')
    topic = models.ForeignKey(to=Topic, to_field='id', on_delete=models.CASCADE,
                              help_text='关联话题表')
    up = models.IntegerField(default=0, help_text='支持')
    down = models.IntegerField(default=0, help_text='反对')
    def __str__(self):
        return '%d : %d' % (self.id, self.content[0:20])

2、创建model实例对象

>>> user = User.objects.get(username='lixiaowu')
>>> topic = Topic(title='first topic', content='this is the first topic', user=user)
>>> topic.save()
>>> topic2 = Topic.objects.create(title='second topic', content='this is the second topic', user=user)
>>> comment2 = Comment.objects.create(content='good', topic=topic2, up=28,down=75)

3、查看数据表

mysql> select * from post_topic;
+----+----------------------------+----------------------------+--------------+--------------------------+-----------+---------+
| id | create_time                | last_modfied               | title        | content                  | is_online | user_id |
+----+----------------------------+----------------------------+--------------+--------------------------+-----------+---------+
|  1 | 2021-05-23 12:52:03.056656 | 2021-05-23 12:52:03.056656 | first topic  | this is the first topic  |         1 |       1 |
|  2 | 2021-05-23 12:54:12.101493 | 2021-05-23 12:54:12.101493 | second topic | this is the second topic |         1 |       1 |
|  3 | 2021-05-23 12:56:23.874125 | 2021-05-23 12:56:23.874125 | third topic  | this is the third topic  |         1 |       1 |
+----+----------------------------+----------------------------+--------------+--------------------------+-----------+---------+
3 rows in set (0.00 sec)

mysql> select * from auth_user;
+----+------------+----------------------------+--------------+----------+------------+-----------+--------------+----------+-----------+----------------------------+
| id | password   | last_login                 | is_superuser | username | first_name | last_name | email        | is_staff | is_active | date_joined                |
+----+------------+----------------------------+--------------+----------+------------+-----------+--------------+----------+-----------+----------------------------+
|  1 | lmx082902* | 2021-05-24 00:00:00.000000 |            0 | lixiaowu | li         | xiaowu    | 1232e23ewqe2 |        1 |         1 | 2020-05-24 00:00:00.000000 |
+----+------------+----------------------------+--------------+----------+------------+-----------+--------------+----------+-----------+----------------------------+
1 row in set (0.00 sec)

mysql>

4、数据查询

单实例查询
Topic.objects.get(topic='first topic')

多条件查询
Topic.objects.get(id=1, topic='first topic')

获取所有数据
Topic.objects.all()

逆序输出 
Topic.objects.reverse()

过滤输出
Topic.objects.filter(id__gte=2)

5、RawQuerySet查询

代码中使用raw函数直接执行sql语句

>>> for comment in Comment.objects.raw('select * from post_comment'):
...     print('%d: %s' % (comment.id, comment.content))
...
1: very good
2: good
3: so bad
4: so bad
>>>

6、其他操作

查询返回值的长度
>>> len(Comment.objects.all())
4
>>> Comment.objects.all().count()
4
>>>

判断是否包含对象
>>> Comment.objects.filter(id__gte=30).exists()
False
>>>

更新对象
>>> comment = Comment.objects.get(id=1)
>>> comment.up = 90
>>> comment.save()

>>> Comment.objects.filter(id=1).update(up=20,down=99)
1
>>>

删除数据
>>> Comment.objects.filter(id=1).delete()
(1, {'post.Comment': 1})
>>>
  • 作者:远去的栀子花
  • 原文链接:https://blog.csdn.net/u012967763/article/details/117200605
    更新时间:2022-08-10 10:35:18