def _delete_and_recreate_tags(slug): source_demo = Submission.objects.using('default').get(slug=slug) destination_demo = Submission.objects.using('new').get(slug=slug) source_type, destination_type = _get_demo_content_types() source_tags = source_demo.taggit_tags.all() source_tags_names = [tag.name for tag in source_tags] destination_tags = destination_demo.taggit_tags.using('new').all() destination_tags_names = [tag.name for tag in destination_tags] if source_tags_names == destination_tags_names: logger.info( "%s: Found %s matching tag(s): %s" % (source_demo.slug, len(destination_tags), destination_tags_names)) return destination_tags else: dest_demo_tagged_items = TaggedItem.objects.using('new').filter( tag__in=[tag for tag in destination_tags], object_id=destination_demo.id, content_type=destination_type) dest_demo_tagged_items.using('new').delete() logger.info("%s: Migrating %s tag(s): %s" % (source_demo.slug, len(source_tags), source_tags_names)) for source_tag in source_tags: try: destination_tag = (Tag.objects.using('new').get( name=source_tag.name)) except Tag.DoesNotExist: destination_tag = Tag(name=source_tag.name) destination_tag.save(using='new') destination_demo_tag = TaggedItem(content_type=destination_type, object_id=destination_demo.id, tag=destination_tag) destination_demo_tag.save(using='new') return destination_tags
def done(self, form_list, form_dict, **kw): """Overriden to do a job""" options = self.get_options() data = {} for f in form_list: data.update(f.cleaned_data) data.update(self.request.session[options['session_prefix']]) content_type = ContentType.objects.get_by_natural_key(data['app_label'], data['model']) ids = data['ids'] model = content_type.model_class() objs = model.objects.filter(pk__in=ids) ids = list(objs.values_list('pk', flat=True)) cnt = len(ids) tags = [Tag.objects.get_or_create(name=t)[0] for t in data['tags']] existent = TaggedItem.objects.filter(tag__in=tags, content_type=content_type, object_id__in=ids) if data['clear']: existent.delete() messages.add_message(self.request, messages.INFO, _("Untagged %(number)s %(model_name)s") % { "number": cnt, "model_name": model_ngettext(model._meta, cnt) }) else: existent_tags = set([(e.tag_id, e.object_id) for e in existent]) tagged_items = [ TaggedItem(tag=tag, content_type=content_type, object_id=o.id) for o in objs for tag in tags if not (tag.id, o.id) in existent_tags ] TaggedItem.objects.bulk_create(tagged_items) messages.add_message(self.request, messages.INFO, _("Tagged %(number)s %(model_name)s") % { "number": cnt, "model_name": model_ngettext(model._meta, cnt) }) return HttpResponseRedirect(data['referer'])