Python · 1 分钟阅读
构建 post 应用的数据模型
以 BBS 场景为例:Topic(话题)、Comment(评论),再用一个抽象基类承载公共字段。
业务需求
- 用户发布 话题(Topic)
- 对话题发表 评论(Comment)
- 评论可被点赞 / 反对
抽象基类
post/models.py:
from django.db import models
class BaseModel(models.Model):
"""公共字段:创建时间、最近修改时间。"""
class Meta:
abstract = True
ordering = ["-created_time"]
created_time = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
raise NotImplementedError
| 选项 | 作用 |
|---|---|
abstract = True |
抽象类,不创建表 |
ordering |
默认排序规则 |
auto_now_add |
首次保存时写入当前时间 |
auto_now |
每次保存都更新为当前时间 |
Topic
from django.contrib.auth.models import User
class Topic(BaseModel):
title = models.CharField(max_length=255, unique=True)
content = models.TextField()
is_online = models.BooleanField(default=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return f"{self.id}: {self.title[:20]}"
Comment
class Comment(BaseModel):
content = models.CharField(max_length=255)
topic = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name="comments")
up = models.PositiveIntegerField(default=0)
down = models.PositiveIntegerField(default=0)
def __str__(self):
return f"{self.id}: {self.content[:20]}"
related_name="comments"让topic.comments.all()反向查询更直观。
应用迁移
python manage.py makemigrations post
python manage.py sqlmigrate post 0001 # 预览 SQL
python manage.py migrate
表名默认规则:应用名_小写类名,例如 post_topic、post_comment。如需自定义:
class Meta:
db_table = "topic"