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

前端 未结 1 1063
失恋的感觉
失恋的感觉 2020-12-18 08:22

I am trying to enhance the django admin interface similar to what has been done in the accepted answer of this SO post. I have a many-to-many relationship between a Us

相关标签:
1条回答
  • 2020-12-18 08:29

    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()
    
    0 讨论(0)
提交回复
热议问题