2014-09-25 59 views
0

我試圖用celery任務將值保存到django中的文本字段,但如果文本字段有值,我想將新值附加到舊值。將新值附加到舊值

這裏是我的模型:

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)')

+0

這是否行'個人資料= Profile.objects.get(配置=配置文件)'真正的個人資料? 'Profile'沒有一個叫'profile'的屬性。 – 2014-09-25 09:03:43

+0

是的,它的確如此。現在更新了問題代碼,所以更清楚。 – 2014-09-25 09:06:59

+0

你有沒有試過這個明顯的選擇:'profile.info ='{} \ n {}'.format(profile.info,data ['info'])'? – 2014-09-25 09:15:07

回答

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()