Django admin interface: using horizontal_filter with ManyToMany field with intermediate table

一世执手 提交于 2019-12-01 01:00:26

I could find a way of solving this issue. The idea is:

  1. Create new entries in the Membership table if and only if they are new (otherwise it would erase the existing data for the other fields in the Membership table)
  2. Remove entries that were deselected from the Membership table

To do this, I replaced:

if project.pk:
    project.userprofile_set = self.cleaned_data['userprofiles']
    self.save_m2m()

By:

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!