7

django-taggit を使用しているモデルがあります。このモデルにタグを追加する South データ移行を実行したいと考えています。ただし、.tags マネージャーは、通常の Django orm の代わりに South orm['myapp.MyModel'] API を使用する必要がある South 移行内からは利用できません。

post.tags が None であるため、このようなことをすると例外がスローされます。

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

South のデータ移行内から taggit を使用してタグを作成して適用することはできますか? もしそうなら、どのように?

4

2 に答える 2

8

はい、これを行うことができますが、 メソッドを使用する代わりにTaggitの API を直接使用する (つまり、Tagおよび を作成する) 必要があります。TaggedItemadd

taggitまず、この移行にフリーズすることから始める必要があります。

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

次に、転送メソッドは次のようになります (すべての 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
            )
于 2012-12-11T19:59:20.010 に答える
0

ないと思います。最初に移行を実行してから、投稿オブジェクトにデフォルトのタグを追加する必要があります。タグはモデルに関連付けられていません。これらはモデル オブジェクトに関連付けられています。

于 2012-12-03T22:04:40.773 に答える