|
| 1 | +""" |
| 2 | +To understand why this file is here, please read: |
| 3 | +
|
| 4 | +http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django |
| 5 | +""" |
| 6 | +from django.conf import settings |
| 7 | +from django.db import migrations |
| 8 | + |
| 9 | + |
| 10 | +def _update_or_create_site_with_sequence(site_model, connection, domain, name): |
| 11 | + """Update or create the site with default ID and keep the DB sequence in sync.""" |
| 12 | + site, created = site_model.objects.update_or_create( |
| 13 | + id=settings.SITE_ID, |
| 14 | + defaults={ |
| 15 | + "domain": domain, |
| 16 | + "name": name, |
| 17 | + }, |
| 18 | + ) |
| 19 | + if created: |
| 20 | + # We provided the ID explicitly when creating the Site entry, therefore the DB |
| 21 | + # sequence to auto-generate them wasn't used and is now out of sync. If we |
| 22 | + # don't do anything, we'll get a unique constraint violation the next time a |
| 23 | + # site is created. |
| 24 | + # To avoid this, we need to manually update DB sequence and make sure it's |
| 25 | + # greater than the maximum value. |
| 26 | + max_id = site_model.objects.order_by('-id').first().id |
| 27 | + with connection.cursor() as cursor: |
| 28 | + cursor.execute("SELECT last_value from django_site_id_seq") |
| 29 | + (current_id,) = cursor.fetchone() |
| 30 | + if current_id <= max_id: |
| 31 | + cursor.execute( |
| 32 | + "alter sequence django_site_id_seq restart with %s", |
| 33 | + [max_id + 1], |
| 34 | + ) |
| 35 | + |
| 36 | + |
| 37 | +def update_site_forward(apps, schema_editor): |
| 38 | + """Set site domain and name.""" |
| 39 | + Site = apps.get_model("sites", "Site") |
| 40 | + _update_or_create_site_with_sequence( |
| 41 | + Site, |
| 42 | + schema_editor.connection, |
| 43 | + "chat.opensource.legal", |
| 44 | + "Chat All The Docs", |
| 45 | + ) |
| 46 | + |
| 47 | + |
| 48 | +def update_site_backward(apps, schema_editor): |
| 49 | + """Revert site domain and name to default.""" |
| 50 | + Site = apps.get_model("sites", "Site") |
| 51 | + _update_or_create_site_with_sequence( |
| 52 | + Site, |
| 53 | + schema_editor.connection, |
| 54 | + "example.com", |
| 55 | + "example.com", |
| 56 | + ) |
| 57 | + |
| 58 | + |
| 59 | +class Migration(migrations.Migration): |
| 60 | + |
| 61 | + dependencies = [("sites", "0002_alter_domain_unique")] |
| 62 | + |
| 63 | + operations = [migrations.RunPython(update_site_forward, update_site_backward)] |
0 commit comments