python - 保存时使用主键创建字段描述

标签 python django

我对 Django 还很陌生,所以请耐心等待...

我想在保存时根据该条目的主键在同一个表中设置另一个字段。更准确地说:

我的模型(示例):

class Status(models.Model):
    status_name = models.CharField(max_length=10)
    status_description = models.CharField(max_length=30)

    def __str__(self):
        return self.status_description

我希望 status_description 类似于:

"The status is " + status_name + ", while the ID is: " + str([Primary key])

显然,在插入记录之前我不会拥有主键。有没有办法创建一个函数,在插入记录后立即更新记录?

我尝试过重写 save-方法,但如果再次 save() ,这显然会产生无限循环。

(请注意,这是一个示例,我实际上想做的是创建与该记录相关的一些 ID 的哈希值,包括记录的主键。如果我可以这样做,我可能可以完成剩下的工作。数据库上的触发器对我来说不起作用。)

感谢您的帮助!

最佳答案

您可以使用django接收器来使用post_save。还要在 status_description 字段中定义 null=True, Blank=True

from django.db.models.signals import post_save
from django.dispatch import receiver

class Status(models.Model):
    status_name = models.CharField(max_length=10)
    status_description = models.CharField(max_length=30, null=True, blank=True)

@receiver(post_save, sender=Status):
def status_desc(sender, instance, **kwargs):
    instance.status_description = "The status is " + instance.status_name + ", while the ID is: " + str(instance.id)
    # save the instance
    instance.save()

关于python - 保存时使用主键创建字段描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33781231/

相关文章:

python - 在 Python 中从 Unicode Web Scrape 输出 ascii 文件

java - 在java代码中使用python库

python - 如果识别出汽车拍照

python - 在单个 View 中序列化多个模型

python - 文件上传:Trim-last-few-Characters-Save Extension

python在写入文件时在第一行打印一个空行

python - 如何在 Open3d 中对齐/注册两个网格? (Python)

Django 模板对象类型

database - Django 管理页面的替代品

python - “str”对象不可调用/django/contrib/auth/views.py in password_reset,第 185 行