Django管理界面:对带有中间表的ManyToMany字段使用horizo​​ntal_filter

Django管理界面:对带有中间表的ManyToMany字段使用horizo​​ntal_filter,第1张

Django管理界面:对带有中间表的ManyToMany字段使用horizo​​ntal_filter

我可以找到解决此问题的方法。这个想法是:

  1. 当且仅当它们是新的时,才在Membership表中创建新条目(否则将删除Membership表中其他字段的现有数据)
  2. 删除从“成员资格”表中取消选择的条目

为此,我替换了:

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()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5667191.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存