2016-08-11 2 views
0

아래 코드를 사용하여 상태를 업데이트하고 있습니다.django에서 모델 객체를 업데이트하는 방법은 무엇입니까?

current_challenge = UserChallengeSummary.objects.filter(user_challenge_id=user_challenge_id).latest('id') 
current_challenge.update(status=str(request.data['status'])) 

나는 오류가 아래에 무엇입니까 :

'UserChallengeSummary' object has no attribute 'update'

의 경우이 오류를 해결 : 내가 솔루션을 발견 레코드를 업데이트 할 수있는 또 다른 방법은

current_challenge.status = str(request.data['status']) 
current_challenge.save() 

을 있습니까?

+0

내가 아는 한, 당신의 해결책은 장고를 위해 보통이다 – Compadre

답변

0

latest() 메서드는 업데이트 메서드가없는 UserChallengeSummary의 인스턴스 인 최신 개체를 반환합니다.

단일 개체를 업데이트하는 경우 사용자의 방법이 표준입니다.

update() 메서드는 한 번에 여러 개체를 업데이트하는 데 사용되므로 QuerySet 인스턴스에서 작동합니다.

1

당신의 작업 솔루션은 @Compadre가 이미 말했듯이, 장고에서 일반적으로 사용되는 방법입니다.

가끔씩 (예 : 테스트에서) 한 번에 여러 필드를 업데이트하는 것이 유용합니다.

def update_attrs(instance, **kwargs): 
    """ Updates model instance attributes and saves the instance 
    :param instance: any Model instance 
    :param kwargs: dict with attributes 
    :return: updated instance, reloaded from database 
    """ 
    instance_pk = instance.pk 
    for key, value in kwargs.items(): 
     if hasattr(instance, key): 
      setattr(instance, key, value) 
     else: 
      raise KeyError("Failed to update non existing attribute {}.{}".format(
       instance.__class__.__name__, key 
      )) 
    instance.save(force_update=True) 
    return instance.__class__.objects.get(pk=instance_pk) 

사용 예 : 당신은, 당신은 함수에서 instance.save()를 제거 할 수 있습니다

current_challenge = update_attrs(current_challenge, 
           status=str(request.data['status']), 
           other_field=other_value) 
           # ... etc. 

(함수 호출 후 명시 적으로 호출하는) 이러한 경우를 위해 나는 간단한 도우미를 작성했습니다.

+0

빠른 답장을 보내 주셔서 감사합니다. 나는 내 문제를 해결하기 위해 당신의 솔루션을 사용합니다. –

+0

차라리 모델을 다시 업데이트하기 위해 '장바구니'장고 방법을 살펴 보는 것이 좋습니다. 사용하는 것이 좋습니다. 나는 위에 제공된 코드를 사용하여 나의 unittests를 더 짧게 유지한다. –

+0

예, 원시 쿼리를 사용할 수 있습니다. ORM 쿼리를 사용하면 쉽게 달성 할 수 있습니다. –

관련 문제