Django 管理后台:字段改变时发送信号

2 投票
1 回答
2572 浏览
提问于 2025-04-17 01:52

我需要在“状态”这个表单字段被更新时才触发一个信号。现在这个信号虽然能正常工作,但无论表单有没有变化,它都会被触发。

下面是我在admin.py中为OrderAdmin类重写的save_model方法:

def save_model(self, request, obj, form, change):
    if not change:
        if not request.user.is_superuser:
            obj.organization = request.user
    if Order().is_dirty():
        custom_signals.notify_status.send(sender=self, status=obj.status)  
    obj.save()  

这是我的模型:

class Order(DirtyFieldsMixin, models.Model):

StatusOptions = (
  ('Pending Confirmation', 'Pending Confirmation'),
  ('Confirmed', 'Confirmed'),
  ('Modified', 'Modified'),
  ('Placed', 'Placed'),
  ('En Route', 'En Route'),
  ('Completed', 'Completed'),
  ('Cancelled', 'Cancelled'),
  )

organization = models.ForeignKey(User, related_name='orders', default=1, help_text='Only visible to admins.')
status = models.CharField(max_length=50, choices=StatusOptions, default=1, help_text='Only visible to admins.')
order_name = models.CharField(max_length=22, blank=True, help_text='Optional. Name this order for easy reference (example: Munchies)')
contact_person = models.ForeignKey(Contact, help_text='This person is in charge of the order. We may contact him/her regarding this order.')
delivery_date = models.DateField('delivery day', help_text='Please use YYYY-MM-DD format (example: 2011-11-25)')

1 个回答

3

你可以尝试重写 ModelAdmin.get_object 这个方法,给你的实例添加一个标记:

def get_object(self, request, object_id):
    o = super(Order, self).get_object(request, object_id)
    if o:
        o._old_status = o.status
    return o

现在你可以在 save_model 里使用 if o.status != o._old_status 这个判断了。

撰写回答