2014-09-25 2 views
0

셀로리 작업으로 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'이라는 속성을 가지고 있지 않습니다. –

+0

네, 맞습니다. 지금 질문 코드가 업데이트되어 더 명확합니다. –

+0

명백한 옵션을 시도해 보셨습니까 : 'profile.info ='{} \ n {} '. format (profile.info, data ['info '])'? –

답변

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() 
관련 문제