将新值附加到旧值

时间:2014-09-25 08:39:56

标签: python django

我尝试使用芹菜任务将值保存到django中的文本字段,但如果textfield有值,我想将新值附加到旧值。

这是我的模特:

class Profile(models.Model):
    username = models.CharField(max_length=200)
    info = models.TextField(blank=True)

以下是我的尝试:

 @shared_task
def update_profile(data, profile_username):

    #Get the profile
    profile = Profile.objects.get(username=profile_username) #(WORKING)

    #Check if info is in dataset
    if 'info' in data: #(WORKING)

        #Check if there is an old value
        if profile.info:  #(WORKING)

            #Old value found

            old_info = profile.info

            #Append old and new value
            new_info = '{}\n{}'format(old_info, data['info'])

            profile.info = new_info


        else:
            #No old value fond, save the new value
            profile.info = data['info'] #(WORKING)

    #Save profile
    profile.save() #(WORKING)

如果该字段没有旧值,我可以保存新值,但是当我尝试将旧值和新值保存在一起时,我将无法工作!我只能保存其中一个,而不是像我想的那样“更新”该字段。

编辑:

我现在看到new_info = '{}\n{}'format(old_info, data['info'])正在运行,但我收到此错误:UnicodeEncodeError('ascii', u'Test\xf8', 128, 129, 'ordinal not in range(128)')

1 个答案:

答案 0 :(得分:1)

您需要简化循环,以便可以正确调试它。使用get(一种词典方法)来获取密钥,如果密钥不存在,您可以为其分配默认值。

把这些放在一起,你的代码现在是:

def update_profile(data, profile_username):

    profile = Profile.objects.get(username=profile_username) #(WORKING)
    profile.info = u'{}\n{}'.format(profile.info, data.get('info', '').encode('utf-8'))
    profile.save()
相关问题