You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DjangoBlog/comments/models.py

60 lines
2.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 导入Django配置、数据库模型、时间工具和翻译工具
from django.conf import settings
from django.db import models
from django.utils.timezone import now # 获取当前时区时间的工具
from django.utils.translation import gettext_lazy as _ # 国际化翻译工具,用于多语言支持
# 导入博客文章模型,评论将与文章关联
from blog.models import Article
# 创建评论模型(数据库表结构的抽象)
class Comment(models.Model):
# 评论正文文本字段最大长度300 verbose_name为'正文'(后台显示名称)
body = models.TextField('正文', max_length=300)
# 创建时间:日期时间字段,使用当前时区时间作为默认值,国际化翻译字段名为'creation time'
creation_time = models.DateTimeField(_('creation time'), default=now)
# 最后修改时间:日期时间字段,默认值为当前时间(后续可通过代码更新)
last_modify_time = models.DateTimeField(_('last modify time'), default=now)
# 评论作者外键关联到Django内置用户模型settings.AUTH_USER_MODEL
# on_delete=models.CASCADE表示如果用户被删除其评论也会被级联删除
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
verbose_name=_('author'),
on_delete=models.CASCADE)
# 关联文章外键关联到博客文章模型Article
# on_delete=models.CASCADE表示如果文章被删除其下所有评论也会被级联删除
article = models.ForeignKey(
Article,
verbose_name=_('article'),
on_delete=models.CASCADE)
# 父评论:自关联外键,用于实现评论回复功能
# 'self'表示关联到当前模型自身blank=True和null=True允许为空即顶级评论
# 父评论被删除时,子评论也会被级联删除
parent_comment = models.ForeignKey(
'self',
verbose_name=_('parent comment'),
blank=True,
null=True,
on_delete=models.CASCADE)
# 是否启用:布尔字段,默认不启用(可能用于评论审核功能)
# blank=False和null=False表示该字段必填且不能为NULL
is_enable = models.BooleanField(_('enable'),
default=False, blank=False, null=False)
# 模型元数据配置(影响模型的整体行为和显示)
class Meta:
ordering = ['-id'] # 默认排序按ID降序最新评论在前
verbose_name = _('comment') # 模型的单数显示名称(用于后台)
verbose_name_plural = verbose_name # 模型的复数显示名称(与单数相同)
get_latest_by = 'id' # 指定通过id字段获取最新记录
# 模型的字符串表示:在后台和打印对象时显示评论正文
def __str__(self):
return self.body