由 Django 中的字段更改触发的操作 [英] Actions triggered by field change in Django

查看:13
本文介绍了由 Django 中的字段更改触发的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的一个模型中的某个字段发生更改时,我如何进行操作?在这种特殊情况下,我有这个模型:

How do I have actions occur when a field gets changed in one of my models? In this particular case, I have this model:

class Game(models.Model):
    STATE_CHOICES = (
        ('S', 'Setup'),
        ('A', 'Active'),
        ('P', 'Paused'),
        ('F', 'Finished')
        )
    name = models.CharField(max_length=100)
    owner = models.ForeignKey(User)
    created = models.DateTimeField(auto_now_add=True)
    started = models.DateTimeField(null=True)
    state = models.CharField(max_length=1, choices=STATE_CHOICES, default='S')

并且我希望在状态从 Setup 变为 Active 时创建 Units,并使用当前日期时间(除其他外)填充started"字段.

and I would like to have Units created, and the 'started' field populated with the current datetime (among other things), when the state goes from Setup to Active.

我怀疑需要一个模型实例方法,但文档似乎没有太多关于以这种方式使用它们的说明.

I suspect that a model instance method is needed, but the docs don't seem to have much to say about using them in this manner.

更新:我已将以下内容添加到我的游戏类:

Update: I've added the following to my Game class:

    def __init__(self, *args, **kwargs):
        super(Game, self).__init__(*args, **kwargs)
        self.old_state = self.state

    def save(self, force_insert=False, force_update=False):
        if self.old_state == 'S' and self.state == 'A':
            self.started = datetime.datetime.now()
        super(Game, self).save(force_insert, force_update)
        self.old_state = self.state

推荐答案

基本上,你需要重写save方法,检查state字段是否被改变,设置started 如果需要,然后让模型基类完成对数据库的持久化.

Basically, you need to override the save method, check if the state field was changed, set started if needed and then let the model base class finish persisting to the database.

棘手的部分是确定字段是否已更改.查看此问题中的混合和其他解决方案以帮助您解决此问题:

The tricky part is figuring out if the field was changed. Check out the mixins and other solutions in this question to help you out with this:

这篇关于由 Django 中的字段更改触发的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆