当前位置: 首页 > news >正文

django的model中定义【记录修改次数】的这个字段该用什么类型

在这里插入图片描述
django中定义对于某个文章应用的数据库中使用到记录修改次数的这个字段

如models.py中的配置

from django.db import models
from django.utils import timezone
from django.contrib.postgres.fields import ArrayFieldclass Article(models.Model):# Titlestitle_cn = models.CharField(max_length=255, verbose_name='中文标题')title_en = models.CharField(max_length=255, blank=True, null=True, verbose_name='英文标题')# Summariessummary_cn = models.TextField(verbose_name='文章概括中文')summary_en = models.TextField(blank=True, null=True, verbose_name='文章概括英文')# Contentcontent_cn = models.TextField(verbose_name='文章富文本--中文')content_en = models.TextField(blank=True, null=True, verbose_name='文章富文本--英文')# Recommended Products (Repeat 5 times)for i in range(1, 6):locals()[f'product_{i}'] = models.BooleanField(default=False, verbose_name=f'推荐商品{i}【有或无】')locals()[f'product_{i}_title_cn'] = models.CharField(max_length=255, blank=True, null=True, verbose_name=f'推荐商品{i}标题--中文')locals()[f'product_{i}_title_en'] = models.CharField(max_length=255, blank=True, null=True, verbose_name=f'推荐商品{i}标题--英文')locals()[f'product_{i}_summary_cn'] = models.TextField(blank=True, null=True, verbose_name=f'推荐商品{i}商品大致概括--中文')locals()[f'product_{i}_summary_en'] = models.TextField(blank=True, null=True, verbose_name=f'推荐商品{i}商品大致概括--英文')locals()[f'product_{i}_link_cn'] = models.URLField(blank=True, null=True, verbose_name=f'推荐商品{i}的链接--中文')locals()[f'product_{i}_link_en'] = models.URLField(blank=True, null=True, verbose_name=f'推荐商品{i}的链接--英文')# Timestampscreated_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')updated_at = models.DateTimeField(auto_now=True, verbose_name='最后修改时间')change_count = models.PositiveIntegerField(default=0, verbose_name='更改次数')# Modification Timesmodification_times = ArrayField(models.DateTimeField(), blank=True, default=list, verbose_name='修改时间')class Meta:verbose_name = '文章'verbose_name_plural = '文章'def __str__(self):return self.title_cndef save(self, *args, **kwargs):if self.pk:self.change_count += 1self.modification_times.append(timezone.now())super().save(*args, **kwargs)

这里面的

modification_times = ArrayField(models.DateTimeField(), blank=True, default=list, verbose_name='修改时间')

Django 的 ArrayField 是为 PostgreSQL 构建的。

SQLite 没有 ArrayField 这个字段类型。

当我还是在测试时,我希望使用SQLite数据库。

要在 SQLite 中存储修改时间列表,一种不同的方法。

我们可以使用文本字段将修改时间存储为序列化的 JSON 列表。

修改时间(存储为 JSON):

models.py模型中的配置

from django.db import models
from django.utils import timezone
import jsonclass Article(models.Model):# Titlestitle_cn = models.CharField(max_length=255, verbose_name='中文标题')title_en = models.CharField(max_length=255, blank=True, null=True, verbose_name='英文标题')# Summariessummary_cn = models.TextField(verbose_name='文章概括中文')summary_en = models.TextField(blank=True, null=True, verbose_name='文章概括英文')# Contentcontent_cn = models.TextField(verbose_name='文章富文本--中文')content_en = models.TextField(blank=True, null=True, verbose_name='文章富文本--英文')# Recommended Products (Repeat 5 times)for i in range(1, 6):locals()[f'product_{i}'] = models.BooleanField(default=False, verbose_name=f'推荐商品{i}【有或无】')locals()[f'product_{i}_title_cn'] = models.CharField(max_length=255, blank=True, null=True, verbose_name=f'推荐商品{i}标题--中文')locals()[f'product_{i}_title_en'] = models.CharField(max_length=255, blank=True, null=True, verbose_name=f'推荐商品{i}标题--英文')locals()[f'product_{i}_summary_cn'] = models.TextField(blank=True, null=True, verbose_name=f'推荐商品{i}商品大致概括--中文')locals()[f'product_{i}_summary_en'] = models.TextField(blank=True, null=True, verbose_name=f'推荐商品{i}商品大致概括--英文')locals()[f'product_{i}_link_cn'] = models.URLField(blank=True, null=True, verbose_name=f'推荐商品{i}的链接--中文')locals()[f'product_{i}_link_en'] = models.URLField(blank=True, null=True, verbose_name=f'推荐商品{i}的链接--英文')# Timestampscreated_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')updated_at = models.DateTimeField(auto_now=True, verbose_name='最后修改时间')change_count = models.PositiveIntegerField(default=0, verbose_name='更改次数')# Modification Times (stored as a JSON list)modification_times = models.TextField(default='[]', verbose_name='修改时间')class Meta:verbose_name = '文章'verbose_name_plural = '文章'def __str__(self):return self.title_cndef save(self, *args, **kwargs):if self.pk:self.change_count += 1mod_times = json.loads(self.modification_times)mod_times.append(timezone.now().isoformat())self.modification_times = json.dumps(mod_times)super().save(*args, **kwargs)def get_modification_times(self):return json.loads(self.modification_times)

注解:

    # Modification Times (stored as a JSON list)modification_times = models.TextField(default='[]', verbose_name='修改时间')def get_modification_times(self):return json.loads(self.modification_times)

modification_times:是 TextField类型,用于将修改时间存储为序列化的 JSON 列表。

get_modification_times:用于将 JSON 列表解析回 Python 列表的帮助程序方法。
通过附加序列化为 JSON 字符串的当前时间来更新 modification_times 字段。

模型的admin.py

# from django.contrib import admin# Register your models here.
from django.contrib import admin
from .models import Articleclass ArticleAdmin(admin.ModelAdmin):list_display = ('title_cn', 'title_en', 'summary_cn', 'summary_en', 'has_recommended_products', 'created_at', 'updated_at', 'change_count')search_fields = ('title_cn', 'title_en')# Define fieldsets to organize form layoutfieldsets = (('标题', {'fields': (('title_cn', 'title_en'),)}),('概括', {'fields': (('summary_cn', 'summary_en'),)}),('内容', {'fields': (('content_cn', 'content_en'),)}),('推荐商品1', {'fields': ('product_1', 'product_1_title_cn', 'product_1_title_en', 'product_1_summary_cn', 'product_1_summary_en', 'product_1_link_cn', 'product_1_link_en')}),('推荐商品2', {'fields': ('product_2', 'product_2_title_cn', 'product_2_title_en', 'product_2_summary_cn', 'product_2_summary_en', 'product_2_link_cn', 'product_2_link_en')}),('推荐商品3', {'fields': ('product_3', 'product_3_title_cn', 'product_3_title_en', 'product_3_summary_cn', 'product_3_summary_en', 'product_3_link_cn', 'product_3_link_en')}),('推荐商品4', {'fields': ('product_4', 'product_4_title_cn', 'product_4_title_en', 'product_4_summary_cn', 'product_4_summary_en', 'product_4_link_cn', 'product_4_link_en')}),('推荐商品5', {'fields': ('product_5', 'product_5_title_cn', 'product_5_title_en', 'product_5_summary_cn', 'product_5_summary_en', 'product_5_link_cn', 'product_5_link_en')}),('时间信息', {'fields': ('created_at', 'updated_at', 'change_count', 'modification_times')}),)readonly_fields = ('created_at', 'updated_at', 'change_count', 'modification_times')def has_recommended_products(self, obj):return any([getattr(obj, f'product_{i}') for i in range(1, 6)])has_recommended_products.boolean = Truehas_recommended_products.short_description = '有推荐商品'# Register the Article model with the ArticleAdmin configuration
admin.site.register(Article, ArticleAdmin)
http://www.lryc.cn/news/505343.html

相关文章:

  • windows openssl编译x64版libssl.lib,编译x64版本libcurl.lib,支持https,vs2015编译器
  • 搭建 Elasticsearch 集群:完整教程
  • 如何实现序列化和反序列化?如何处理对象的生命周期管理?
  • WPF+MVVM案例实战与特效(三十八)- 封装一个自定义的数字滚动显示控件
  • docker安装Redis、docker使用Redis、docker离线安装redis、Redis离线安装
  • 单目动态新视角合成
  • STM32--IO引脚复用
  • Python字符串及正则表达式(十):字符串常用操作、字符串编码转换
  • 前端的Python入门指南(完):错误和异常处理策略及最佳实践
  • LeetCode 2475 数组中不等三元组的数目
  • 【和春笋一起学C++】字符串比较
  • HTTP 协议报文结构 | 返回状态码详解
  • .net winform 实现CSS3.0 泼墨画效果
  • LearnOpenGL学习(高级OpenGL - - 实例化,抗锯齿)
  • 大数据与AI:从分析到预测的跃迁
  • 【CC2530开发基础篇】继电器模块使用
  • C05S07-Tomcat服务架设
  • Java stream groupingBy sorted 实现多条件排序与分组的最佳实践
  • JAVA:代理模式(Proxy Pattern)的技术指南
  • 爬取Q房二手房房源信息
  • Ansible自动化运维(五) 运维实战
  • K-means算法的python实现
  • 客户端(浏览器)vue3本地预览txt,doc,docx,pptx,pdf,xlsx,csv,
  • [SZ901]JTAG高速下载设置(53Mhz)
  • docker springboot 运维部署详细实例
  • Linux 查看目录命令 ls 详细介绍
  • React Native状态管理器Redux、MobX、Context API、useState
  • Three.js资源-模型下载网站
  • linux 添加默认网关
  • 【学习笔记】深入浅出详解Pytorch中的View, reshape, unfold,flatten等方法。