各コンテンツ タイプに対して特定のタグのみが許可される、アプリケーション用のタグ付けシステムを実装しようとしています。
Tag モデルでコンテンツ タイプを設定し、TagAttribution モデルでこの値を使用してみましたが、興味深い結果が得られました。
コード:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.auth.models import User
class Tag(models.Model):
value = models.CharField(max_length=32)
created_by = models.ForeignKey(User)
appliable_to = models.ForeignKey(ContentType)
def __unicode__(self):
return self.value
class TagAttribution(models.Model):
tag = models.ForeignKey(Tag)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('tag__appliable_to', 'object_id')
def __unicode__(self):
return "%s for id %s of class %s" % (self.tag.value, self.object_id, self.content_object.model)
シェルテスト:
ct = ContentType.objects.get(model='company')
tag = Tag()
tag.value = 'value'
tag.created_by = User.objects.get(id=1)
tag.appliable_to = ct
tag.save()
ta = TagAttribution()
ta.tag = tag
ta.object_id = Company.objects.get(id=1).id
ta.content_object = ta.tag.appliable_to
ta.save()
ta
出力:
<TagAttribution: value for id 13 of class company>
この動作がわかりません。会社 ID 1 を使用していたのに、なぜ ID が 13 になったのですか?