code: def sync_groups_from_ad(self):
          
  
          ad_list = ADGroupMapping.objects.values_list('ad_group', 'group')
          mappings = {ad_group: group for ad_group, group in ad_list}
  
          user_ad_groups = set(self.ad_groups.filter(groups__isnull=False).values_list(flat=True))
          all_mapped_groups = set(mappings.values())
          old_groups = set(self.groups.filter(id__in=all_mapped_groups).values_list(flat=True))
          new_groups = set([mappings[x] for x in user_ad_groups])
  
          groups_to_delete = old_groups - new_groups
          if groups_to_delete:
              self.groups.remove(*groups_to_delete)
          groups_to_add = new_groups - old_groups
          if groups_to_add:
              self.groups.add(*groups_to_add)
docs: Determine which Django groups to add or remove based on AD groups.