栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/661076.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号