您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

为此,我替换了:

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()
Go 2022/1/1 18:43:59 有367人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶