我正在使用一些JavaScript库,这些库不允许我传入使用self.full_name
创建的def full_name(self):
想知道如何根据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'
答案 0 :(得分: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}"