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.
Django/models.py

72 lines
2.6 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.contrib.auth.models import AbstractUser
# 导入Django数据库模型
from django.db import models
# 导入URL反向解析函数
from django.urls import reverse
# 导入当前时间获取函数
from django.utils.timezone import now
# 导入国际化翻译函数
from django.utils.translation import gettext_lazy as _
# 导入获取当前站点的工具函数
from djangoblog.utils import get_current_site
# 在这里创建模型
class BlogUser(AbstractUser):
"""自定义用户模型继承自Django抽象用户基类"""
# 昵称字段最大长度100字符允许为空
nickname = models.CharField(
_('nick name'), # 字段显示名称:昵称
max_length=100, # 最大长度
blank=True # 允许为空
)
# 创建时间字段,默认值为当前时间
creation_time = models.DateTimeField(
_('creation time'), # 字段显示名称:创建时间
default=now # 默认值:当前时间
)
# 最后修改时间字段,默认值为当前时间
last_modify_time = models.DateTimeField(
_('last modify time'), # 字段显示名称:最后修改时间
default=now # 默认值:当前时间
)
# 用户来源字段最大长度100字符允许为空
source = models.CharField(
_('create source'), # 字段显示名称:创建来源
max_length=100, # 最大长度
blank=True # 允许为空
)
def get_absolute_url(self):
"""获取用户的绝对URL用于生成用户详情页链接"""
# 使用reverse反向解析URL传入用户名作为参数
return reverse(
'blog:author_detail', # URL模式名称
kwargs={'author_name': self.username} # URL参数作者用户名
)
def __str__(self):
"""对象的字符串表示,返回邮箱地址"""
return self.email
def get_full_url(self):
"""获取用户的完整URL包含域名"""
# 获取当前站点域名
site = get_current_site().domain
# 构建完整URLhttps://域名 + 用户详情页路径
url = "https://{site}{path}".format(
site=site, # 站点域名
path=self.get_absolute_url() # 用户详情页路径
)
# 返回完整URL
return url
class Meta:
"""模型的元数据配置"""
ordering = ['-id'] # 默认排序按ID降序排列
verbose_name = _('user') # 单数显示名称:用户
verbose_name_plural = verbose_name # 复数显示名称:与单数相同
get_latest_by = 'id' # 获取最新记录的依据字段ID