2013-10-31 6 views
0

프로필에 외래 키가 있고 ExternalAttribute 모델과 many-to-many 관계가있는 Connector라는 모델이 있습니다. ExternalAttribute 모델에는 정적 인 속성 오브젝트 목록이 있습니다. 사용자가 프로필에서 ExternalAttribute 모델의 특성을 추가 및 제거 할 수있게하려고합니다.Django : 다 대다 관계 편집

양식에서 ExternalAttribute의 모든 개체를 ModelMultipleChoiceField로 풀다운이 제대로 작동하지만 선택한 특성을 저장하고 개체를 커넥터 모델에 추가 할 수 없습니다. 여기

코드 저장 형태이다 :

ValueError: "<Connector: Connector object>" needs to have a value for field "connector" before this many-to-many relationship can be used. 

내가 함께 일하고 : 나는 형태로 선택한 속성을 저장하려고하면

profile = Profile.objects.get(user = User.objects.get(username=self.cleaned_data['user'])) 

connector = Connector(profile=profile) 
connector.profile = profile 
connector.attributes = self.cleaned_data['selected_attributes'] 
connector.save() 

, 나는 스택 추적에서이 오류가 비효율적 인 데이터베이스이며 이러한 모델을 사용해야합니다. 도와 주셔서 감사합니다.

답변

1

M2M 관계가 저장되기 전에 개체가 저장되어 기본 키가 있어야합니다. 코드를

connector = Connector(profile=profile) 
connector.profile = profile 
connector.save() 
connector.attributes = self.cleaned_data['selected_attributes'] 
connector.save()