我正在尝试创建一个简单的pre_save
函数,但我收到错误kwargs ['instance']。链接未定义等:
为什么吗
我打印出了kwargs ['instance'],我得到了这个:
{'update_fields': None, 'raw': False, 'signal': <django.dispatch.dispatcher.Signal object at 0x10189f750>, 'using': 'default'}
现在这个奇怪的位我打印出实例并获得了名称字段test title name
我的模特:
class Campaign(models.Model):
name = models.CharField(max_length=60)
status = models.CharField(max_length=16, choices=MESSAGE_STATUSES, default="Pending",)
link = models.ForeignKey(Link, related_name='campaign', null=True)
@receiver(pre_save, sender=Campaign)
def my_callback(sender, instance, *args, **kwargs):
print(kwargs)
print(instance)
if kwargs['instance'].link is None:
link = Link()
link.link = "test"
link.save()
kwargs['instance'].link = link
# No need to save, as we're slipping the value in
# before we hit the database.
答案 0 :(得分:3)
只需使用instance.link
即可。 kwargs
不包含'instance'
,因为函数my_callback
将instance
指定为位置参数。
if instance.link is None:
....