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

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

问题描述

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

  class Game(models.Model):
STATE_CHOICES =(
('S','安装'),
('A','活动'),
('P','Paused'),
('F' '完成')

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')
pre>

我想要创建单位,并且当启动状态从安装程序变为活动状态时,开始字段填充了当前的日期时间(除其他外)



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



更新:我已经添加了以下内容我的游戏类:

  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):
如果自己.old_state =='S'和self.state =='A':
self.started = datetime.datetime.now()
super(Game,self).save(force_insert,force_update)
self.old_state = self.state


解决方案

,您需要覆盖 save 方法,检查状态字段是否已更改,设置如果需要,启动,然后让模型基类完成对数据库的持久化。



棘手的部分是弄清楚字段是否更改。查看这个问题中的mixins和其他解决方案,以帮助您解决这个问题:




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')

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

解决方案

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天全站免登陆