我可以找到解决此问题的方法。这个想法是:
- 当且仅当它们是新的时,才在Membership表中创建新条目(否则将删除Membership表中其他字段的现有数据)
- 删除从“成员资格”表中取消选择的条目
为此,我替换了:
if project.pk: project.userprofile_set = self.cleaned_data['userprofiles'] self.save_m2m()
通过:
if project.pk: # Get the existing relationships current_project_selections = Membership.objects.filter(project=project) current_selections = [o.userprofile for o in current_project_selections] # Get the submitted relationships submitted_selections = self.cleaned_data['userprofiles'] # Create new relation in Membership table if they do not exist for userprofile in submitted_selections : if userprofile not in current_selections: Membership(project=project,userprofile=userprofile).save() # Remove the relations that were deselected from the Membership table for project_userprofile in current_project_selections: if project_userprofile.userprofile not in submitted_selections : project_userprofile.delete()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)