69 lines
2.3 KiB
Python
69 lines
2.3 KiB
Python
from django.conf import settings
|
|
from django.db import migrations
|
|
|
|
|
|
def backfill_memberships(apps, schema_editor):
|
|
NetworkMap = apps.get_model('contacts', 'NetworkMap')
|
|
NetworkMapMembership = apps.get_model('contacts', 'NetworkMapMembership')
|
|
Relation = apps.get_model('contacts', 'Relation')
|
|
Contact = apps.get_model('contacts', 'Contact')
|
|
User = apps.get_model('auth', 'User')
|
|
|
|
def backfill_for_owner(owner_id):
|
|
if owner_id is None:
|
|
maps = NetworkMap.objects.filter(owner__isnull=True).order_by('id')
|
|
relations = Relation.objects.filter(owner__isnull=True)
|
|
contact_owner_filter = {'owner__isnull': True}
|
|
else:
|
|
maps = NetworkMap.objects.filter(owner_id=owner_id).order_by('id')
|
|
relations = Relation.objects.filter(owner_id=owner_id)
|
|
contact_owner_filter = {'owner_id': owner_id}
|
|
|
|
if not maps.exists():
|
|
return 0
|
|
if NetworkMapMembership.objects.filter(map__in=maps).exists():
|
|
return 0
|
|
|
|
contact_ids = set()
|
|
for relation in relations.only('source_id', 'target_id'):
|
|
contact_ids.add(relation.source_id)
|
|
contact_ids.add(relation.target_id)
|
|
if not contact_ids:
|
|
return 0
|
|
|
|
contacts = Contact.objects.filter(id__in=contact_ids, **contact_owner_filter)
|
|
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
|
|
|
|
total = backfill_for_owner(None)
|
|
for user in User.objects.all():
|
|
total += backfill_for_owner(user.id)
|
|
if total:
|
|
print(f'Backfilled {total} network map memberships')
|
|
|
|
|
|
class Migration(migrations.Migration):
|
|
|
|
dependencies = [
|
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
|
('contacts', '0011_add_owner'),
|
|
]
|
|
|
|
operations = [
|
|
migrations.RunPython(backfill_memberships, migrations.RunPython.noop),
|
|
]
|