반응형
Django ModelForm에서 저장 메서드 재정의
ModelForm
저장 방법을 재정의하는 데 문제가 있습니다. 이것은 내가받는 오류입니다.
Exception Type: TypeError
Exception Value: save() got an unexpected keyword argument 'commit'
내 의도는 양식에서 3 개 필드에 대한 많은 값을 제출 한 다음 해당 필드의 각 조합에 대한 개체를 만들고 각 개체를 저장하도록하는 것입니다. 올바른 방향으로 도움이되는 넛지는 에이스가 될 것입니다.
파일 models.py
class CallResultType(models.Model):
id = models.AutoField(db_column='icontact_result_code_type_id', primary_key=True)
callResult = models.ForeignKey('CallResult', db_column='icontact_result_code_id')
campaign = models.ForeignKey('Campaign', db_column='icampaign_id')
callType = models.ForeignKey('CallType', db_column='icall_type_id')
agent = models.BooleanField(db_column='bagent', default=True)
teamLeader = models.BooleanField(db_column='bTeamLeader', default=True)
active = models.BooleanField(db_column='bactive', default=True)
파일 forms.py
from django.forms import ModelForm, ModelMultipleChoiceField
from callresults.models import *
class CallResultTypeForm(ModelForm):
callResult = ModelMultipleChoiceField(queryset=CallResult.objects.all())
campaign = ModelMultipleChoiceField(queryset=Campaign.objects.all())
callType = ModelMultipleChoiceField(queryset=CallType.objects.all())
def save(self, force_insert=False, force_update=False):
for cr in self.callResult:
for c in self.campain:
for ct in self.callType:
m = CallResultType(self) # this line is probably wrong
m.callResult = cr
m.campaign = c
m.calltype = ct
m.save()
class Meta:
model = CallResultType
파일 admin.py
class CallResultTypeAdmin(admin.ModelAdmin):
form = CallResultTypeForm
당신에 save
당신은 인수를 가지고 있습니다 commit
. 양식을 재정의하거나 저장중인 내용을 수정하려는 경우 수행 save(commit=False)
하고 출력을 수정 한 다음 자체적으로 저장합니다.
또한 ModelForm은 저장중인 모델을 반환해야합니다. 일반적으로 ModelForm save
은 다음과 같습니다.
def save(self, commit=True):
m = super(CallResultTypeForm, self).save(commit=False)
# do custom stuff
if commit:
m.save()
return m
마지막으로,이 ModelForm의 대부분은 사용자가 사물에 액세스하는 방식 때문에 작동하지 않습니다. 대신 self.callResult
, 당신은 사용해야합니다 self.fields['callResult']
.
업데이트 : 귀하의 답변에 대한 답변 :
곁에 :ManyToManyField
모델에서 s를 사용 하여이 작업을 수행 할 필요가없는 이유는 무엇입니까? 중복 데이터를 저장하고 자신 (및 나 :P
)을 위해 더 많은 작업을 수행하는 것 같습니다 .
from django.db.models import AutoField
def copy_model_instance(obj):
"""
Create a copy of a model instance.
M2M relationships are currently not handled, i.e. they are not copied. (Fortunately, you don't have any in this case)
See also Django #4027. From http://blog.elsdoerfer.name/2008/09/09/making-a-copy-of-a-model-instance/
"""
initial = dict([(f.name, getattr(obj, f.name)) for f in obj._meta.fields if not isinstance(f, AutoField) and not f in obj._meta.parents.values()])
return obj.__class__(**initial)
class CallResultTypeForm(ModelForm):
callResult = ModelMultipleChoiceField(queryset=CallResult.objects.all())
campaign = ModelMultipleChoiceField(queryset=Campaign.objects.all())
callType = ModelMultipleChoiceField(queryset=CallType.objects.all())
def save(self, commit=True, *args, **kwargs):
m = super(CallResultTypeForm, self).save(commit=False, *args, **kwargs)
results = []
for cr in self.callResult:
for c in self.campain:
for ct in self.callType:
m_new = copy_model_instance(m)
m_new.callResult = cr
m_new.campaign = c
m_new.calltype = ct
if commit:
m_new.save()
results.append(m_new)
return results
이것은 CallResultTypeForm
필요한 경우를 대비하여의 상속을 허용 합니다.
참고 URL : https://stackoverflow.com/questions/817284/overriding-the-save-method-in-django-modelform
반응형
'Nice programing' 카테고리의 다른 글
부울에 대한 ng-repeat 필터 (0) | 2020.12.03 |
---|---|
부울 목록에서 True 값 인덱스 가져 오기 (0) | 2020.12.03 |
SQL IN은 성능에 좋지 않습니까? (0) | 2020.12.03 |
Boost로 ini 파일을 구문 분석하는 방법 (0) | 2020.12.03 |
지난달에 대한 git 커밋 로그를 생성하고 CSV로 내보내려면 어떻게해야합니까? (0) | 2020.12.03 |