Django/Python更新字段值(在模型保存期间) [英] Django/Python update field values (during model save)

查看:48
本文介绍了Django/Python更新字段值(在模型保存期间)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在保存django模型时,我试图将其大写.查看此问题,其中有答案:

I am trying to capitalize a number of fields in my django models, when they are saved. Looking at this question, which had this answer:

class Blog(models.Model):
    name = models.CharField(max_length=100)
    def save(self):
        self.name = self.name.title()
        super(Blog, self).save()

这很好用,但是,在每次保存中,如果我想重复多次,都需要一些额外的输入.因此,我想创建一个在保存步骤中将字段作为输入并将其重新保存为大写的函数.所以我写了这个来测试它:

This works fine, however, in each save, this requires some extra typing, if I want to repeat this multiple times. So I would like to create a function that takes fields as an input and re-saves them as uppercase, during the save step. So I wrote this to test it:

def save(self):
    for field in [self.first_name, self.last_name]:
        field = field.title()
    super(Artist,self).save()

但是,如果我以前考虑过,我会意识到这只会覆盖 field 变量.我想循环浏览变量列表以进行更改.我知道有些函数可以在不使用 = 的情况下更改其值.他们怎么做到的?我能做到吗?

However, if I had thought about it before, I would have realized that this simply overwrite the field variable. I want to cycle through a list of variables to change them. I know that some functions change the value in place, without using the =. How do they do this? Could I achieve that?

还是有一些更简单的方法来做我正在做的事情?我走错路了吗?

Or is there some simpler way to do what I am doing? I am going the wrong way?

解决方案:从第一个答案开始,我做了函数:

SOLUTION: From the first answer, I made the function:

def cap(self, *args):
    for field in args:
        value = getattr(self, field)
        setattr(self, field, value.title())

以及在我的模型中:

def save(self):
    cap(self,'first_name', 'last_name')
    super(Artist,self).save()

推荐答案

您可以使用setattr(self,my_field_name,value)来实现.

You can use setattr(self, my_field_name, value) to achieve this.

for field in ['first_name', 'last_name']: 
    value = getattr(self, field)
    setattr(self, field, value.title())

由于字符串在Python中是不可变的,因此您将无法就地修改值.

You won't be able to modify the value in-place as strings are immutables in Python.

这篇关于Django/Python更新字段值(在模型保存期间)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆