【问题标题】:Django detect changes to multiple fields in same modelDjango 检测同一模型中多个字段的更改
【发布时间】:2018-06-27 22:37:26
【问题描述】:

我正在使用一些 javascript 库,它们不允许我传入使用 def full_name(self): 创建的 self.full_name

想知道我应该如何根据对 3 个名称字段中任何一个的更改(或创建)来更新 full_name 字段。

class Employee(models.Model):
  first_name = StringProperty(max_length=25)
  middle_name = StringProperty(max_length=25)
  last_name = StringProperty(max_length=50)

  full_name = StringProperty(max_length=100)
  # lots of Icelanders have the same first and last name...
  full_name_includes_middle_name = BooleanProperty(default=False)

现在我正在调查@receiver,created or update_fields 看起来很有希望...

@receiver(post_save, sender=Employee)
def update_full_name(sender, update_fields, created, instance, **kwargs):
  if instance.middle_name_is_part_of_full_name == True:
    if created or update_fields is 'first_name' or 'middle_name' or 'last_name':
      instance.full_name = instance.first_name + " " + instance.middle_name + " " + instance.last_name
      instance.save()
  else:
    if created or update_fields is 'first_name' or 'last_name':
      self.full_name = self.first_name + " " + self.last_name
      instance.save()

^ 但这给出了错误:

update_full_name() missing 1 required positional argument: 'update_fields'

【问题讨论】:

  • 是的,信号监听器 @receiverupdate_fields 可以工作。
  • @YusefBH 用一些接收器代码更新了我的问题。试图弄清楚如何在中传递这些字段

标签: django django-models django-signals


【解决方案1】:

在这种情况下,创建或更新操作之间没有区别。

你可以试试这个:

@receiver(pre_save, sender=Employee)
def update_full_name(sender, instance, **kwargs):
  if instance.middle_name_is_part_of_full_name == True:
      instance.full_name = f"{instance.first_name} {instance.middle_name} {instance.last_name}"
  else:
      instance.full_name = f"{instance.first_name} {instance.last_name}"

【讨论】:

  • 非常感谢 =) 我现在正在尝试。 hooked() got an unexpected keyword argument 'update_fields'
  • 看起来这个错误是在form.is_valid: form.save之后发生的,我会修复它
  • 是的。 line 206, in save super(Profile, self).save(*args, **kwargs) TypeError: hooked() got an unexpected keyword argument 'update_fields'
  • 这很奇怪,可以尝试不使用update_fields,我更新了答案。
  • 新错误。也许它与从 post_save 调用 save 有关? encoding with 'idna' codec failed (RecursionError: maximum recursion depth exceeded)
猜你喜欢
  • 2011-05-17
  • 1970-01-01
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-08
  • 1970-01-01
  • 2021-07-07
相关资源
最近更新 更多