from contacts.models import Contact, NetworkMap, NetworkMapMembership, Relation def contact_ids_from_relations(relations_qs): contact_ids = set() for relation in relations_qs.only('source_id', 'target_id'): contact_ids.add(relation.source_id) contact_ids.add(relation.target_id) return contact_ids def backfill_map_memberships_for_owner(owner): """Добавляет на первую карту владельца контакты из его связей, если участников ещё нет.""" if owner is None: maps = NetworkMap.objects.filter(owner__isnull=True).order_by('id') relations = Relation.objects.filter(owner__isnull=True) else: maps = NetworkMap.objects.filter(owner=owner).order_by('id') relations = Relation.objects.filter(owner=owner) if not maps.exists(): return 0 if NetworkMapMembership.objects.filter(map__in=maps).exists(): return 0 contact_ids = contact_ids_from_relations(relations) if not contact_ids: return 0 if owner is None: contacts = Contact.objects.filter(id__in=contact_ids, owner__isnull=True) else: contacts = Contact.objects.filter(id__in=contact_ids, owner=owner) target_map = maps.first() created = 0 for contact in contacts: _, was_created = NetworkMapMembership.objects.get_or_create( map=target_map, contact=contact, defaults={ 'life_sphere': 'other', 'network_circle': 'productivity', 'importance': 3, 'conflict_involvement': 3, }, ) if was_created: created += 1 return created def backfill_all_map_memberships(): from django.contrib.auth import get_user_model User = get_user_model() total = 0 total += backfill_map_memberships_for_owner(None) for user in User.objects.all(): total += backfill_map_memberships_for_owner(user) return total