我一直在尝试在项目中使用FieldTracker来跟踪从post_save
信号中更新的字段。最初,我考虑使用django-dirtyfields,但是由于它不支持django 2.1,因此我不得不求助于django-model-utils。
下面是项目设置
customer / apps.py
from django.apps import AppConfig
class CustomerConfig(AppConfig):
name = 'customer'
def ready(self):
import customer.signals
customer / models.py
from model_utils import FieldTracker
class CreatedByModel(models.Model):
created_by = models.ForeignKey(User, blank=True, null=True)
modified_by = models.ForeignKey(User, blank=True, null=True)
class Meta:
abstract = True
class Customer(CreatedByModel)
name = models.CharField(max_length=255)
code = models.CharField(max_length=10)
customer_tracker = FieldTracker()
在此处包括管理save_model
代码,因为我在此处明确设置了created_by
和modified_by
字段,并调用了超类save_model
,但我不确定这可能引起问题
customer / admin.py
class CustomerAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if not obj.created_by:
obj.created_by = request.user
else:
obj.modified_by = request.user
super().save_model(request, obj, form, change)
customer / signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Customer
@receiver(post_save, sender=Customer)
def notify_api_clients(sender, **kwargs):
print('hit inside tracker {}' . format(sender.customer_tracker.changed()))
我在尝试保存说明AttributeError
的Customer对象时收到'FieldTracker' object has no attribute 'changed'
错误。
我不确定这里可能是什么问题。感谢任何指导。
更新
经过几次测试,我可以使用post_save
自变量**kwargs
中的实例调用它,然后按以下方法获取changed()字段
@receiver(post_save, sender=Customer)
def notify_api_clients(sender, **kwargs):
if 'instance' in kwargs:
instance = kwargs['instance']
print('changed fields: {}' . format(instance.customer_tracker.changed()))
我希望这可能是我所缺少的。