Improved tags

This commit is contained in:
Angel Rey 2020-09-21 11:50:26 -05:00
parent 0158efb1d0
commit 62c9028212
11 changed files with 172 additions and 10 deletions

View file

@ -0,0 +1,89 @@
# Generated by Django 3.0.8 on 2020-09-15 20:06
from django.db import migrations, models
from django.contrib.contenttypes.models import ContentType
from django.utils.text import slugify
import django.db.models.deletion
import taggit.managers
def forwards_func(apps, schema_editor):
SnapshotModel = apps.get_model("core", "Snapshot")
TaggedItemModel = apps.get_model("core", "TaggedItem")
TagModel = apps.get_model("taggit", "Tag")
contents = ContentType.objects.all()
try:
ct = ContentType.objects.filter(app_label="core", model="snapshot")
except model.DoesNotExist: # Be explicit about exceptions
ct = None
db_alias = schema_editor.connection.alias
snapshots = SnapshotModel.objects.all()
for snapshot in snapshots:
tags = snapshot.tags
tag_set = (
set(tag.strip() for tag in (snapshot.tags_old or '').split(','))
)
tag_list = list(tag_set) or []
for tag in tag_list:
new_tag, created = TagModel.objects.get_or_create(name=tag, slug=slugify(tag))
TaggedItemModel.objects.get_or_create(
content_type_id=ct[0].id,
object_id=snapshot.id,
tag=new_tag
)
def reverse_func(apps, schema_editor):
SnapshotModel = apps.get_model("core", "Snapshot")
TaggedItemModel = apps.get_model("core", "TaggedItem")
TagModel = apps.get_model("taggit", "Tag")
ct = ContentType.objects.get(app_label="core", model="snapshot")
db_alias = schema_editor.connection.alias
snapshots = SnapshotModel.objects.all()
for snapshot in snapshots:
for tag in tags:
tagged_items = TaggedItemModel.objects.filter(
object_id=snapshot.id,
).delete()
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('taggit', '0003_taggeditem_add_unique_index'),
('core', '0005_auto_20200728_0326'),
]
operations = [
migrations.RenameField(
model_name='snapshot',
old_name='tags',
new_name='tags_old',
),
migrations.CreateModel(
name='TaggedItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('object_id', models.UUIDField(db_index=True, verbose_name='object ID')),
('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='core_taggeditem_tagged_items', to='contenttypes.ContentType', verbose_name='content type')),
('tag', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='core_taggeditem_items', to='taggit.Tag')),
],
options={
'verbose_name': 'Tag',
'verbose_name_plural': 'Tags',
},
),
migrations.AddField(
model_name='snapshot',
name='tags',
field=taggit.managers.TaggableManager(help_text='A comma-separated list of tags.', through='core.TaggedItem', to='taggit.Tag', verbose_name='Tags'),
),
migrations.RunPython(forwards_func, reverse_func),
migrations.RemoveField(
model_name='snapshot',
name='tags_old',
),
]