Use django-taggit within south data migration?
Asked Answered
P

2

7

I have a model that is using django-taggit. I want to perform a South data migration that adds tags to this model. However, the .tags manager is not available from within a South migration where you have to use the South orm['myapp.MyModel'] API instead of the normal Django orm.

Doing something like this will throw an exception because post.tags is None.

post = orm['blog.Post'].objects.latest()
post.tags.add('programming')

Is it possible to create and apply tags with taggit from within a South data migration? If so, how?

Prut answered 3/12, 2012 at 21:48 Comment(0)
A
8

Yes, you can do this, but you need to use Taggit's API directly (i.e. create the Tag and TaggedItem), instead of using the add method.

First, you'll need to start by freezing taggit into this migration:

./manage.py datamigration blog migration_name --freeze taggit

Then your forwards method might look something like this (assuming you have a list of tags you want to apply to all Post objects.

def forwards(self, orm):
    for post in orm['blog.Post'].objects.all():
        # A list of tags you want to add to all Posts.
        tags = ['tags', 'to', 'add']

        for tag_name in tags:
            # Find the any Tag/TaggedItem with ``tag_name``, and associate it
            # to the blog Post
            ct = orm['contenttypes.contenttype'].objects.get(
                app_label='blog',
                model='post'
            )
            tag, created = orm['taggit.tag'].objects.get_or_create(
                name=tag_name)
            tagged_item, created = orm['taggit.taggeditem'].objects.get_or_create(
                tag=tag,
                content_type=ct,
                object_id=post.id  # Associates the Tag with your Post
            )
Ahmed answered 11/12, 2012 at 19:59 Comment(0)
S
0

I think not. You have to first perform the migrations and then add the default tags with the posts objects. Tags are not associated with models. They are associated with model objects.

Sell answered 3/12, 2012 at 22:4 Comment(1)
Yeah, this is a data migration, not a schema migration.Prut

© 2022 - 2024 — McMap. All rights reserved.