重写 save 方法,自动更新 updated_at 字段 注意:如果使用 update_fields 参数,需要明确包含 updated_at
(self, *args, **kwargs)
| 46 | get_latest_by = 'created_at' |
| 47 | |
| 48 | def save(self, *args, **kwargs): |
| 49 | """ |
| 50 | 重写 save 方法,自动更新 updated_at 字段 |
| 51 | |
| 52 | 注意:如果使用 update_fields 参数,需要明确包含 updated_at |
| 53 | """ |
| 54 | # 检查是否是部分更新(指定了 update_fields) |
| 55 | update_fields = kwargs.get('update_fields') |
| 56 | if update_fields: |
| 57 | # 如果指定了 update_fields 但不包含 updated_at,则添加它 |
| 58 | if 'updated_at' not in update_fields: |
| 59 | update_fields = list(update_fields) + ['updated_at'] |
| 60 | kwargs['update_fields'] = update_fields |
| 61 | |
| 62 | # 更新时间戳 |
| 63 | self.updated_at = now() |
| 64 | |
| 65 | super().save(*args, **kwargs) |
| 66 | |
| 67 | |
| 68 | # ===== 视图层 Mixin ===== |
no test coverage detected