在南方数据迁移中使用django-taggit?

Apr*_*che 7 django django-south django-taggit

我有一个使用django-taggit的模型.我想执行一个向此模型添加标记的南数据迁移.但是,在南迁移中无法使用.tags管理器,您必须使用南方orm ['myapp.MyModel'] API而不是普通的Django orm.

执行这样的操作会抛出异常,因为post.tags为None.

post = orm['blog.Post'].objects.latest()
post.tags.add('programming')
Run Code Online (Sandbox Code Playgroud)

是否可以在南数据迁移中使用taggit创建和应用标签?如果是这样,怎么样?

Bra*_*ery 7

是的,你可以这样做,但你需要Taggit直接使用API(即创建TagTaggedItem),而不是使用add方法.

首先,您需要开始冻结taggit此迁移:

./manage.py datamigration blog migration_name --freeze taggit
Run Code Online (Sandbox Code Playgroud)

然后你的转发方法可能看起来像这样(假设你有一个你想要应用于所有Post对象的标签列表.

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
            )
Run Code Online (Sandbox Code Playgroud)