多态性Django-Model关联中的值误差

时间:2011-04-03 17:38:37

标签: python django django-models

我已关注Django ContentTypes,然后我创建了一个用于标记目的的应用。

django-taggittagging

tagging.models.py

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.template.defaultfilters import slugify

class Tag(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(unique=True, max_length=100)

    def __unoicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Tag, self).save(*args, **kwargs)

class TaggedItem(models.Model):
    tag = models.ForeignKey(Tag)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    object = generic.GenericForeignKey('content_type', 'object_id')

    def __unicode__(self):
        return self.tag.name

blog.models.py

class Article(models.Model):
    title = models.CharField(max_length=250)
    content = models.TextField()

    ##
    tags = generic.GenericRelation(TaggedItem)

blog.views.py

article = Article.objects.create(user=request.user)
article.title = form.cleaned_data['title']
article.body = form.cleaned_data['body']

##
tag_names = form.cleaned_data['tags'].split()
for tag_name in tag_names:
    tagged = TaggedItem(object=article, tag=tag_name)
    tagged.save()
article.save()

因此,当我保存或创建新的article时,我会收到此错误:

Cannot assign "u'browser'": "TaggedItem.tag" must be a "Tag" instance.

浏览器是一个标记字符串!!!

我认为此错误已打印,因为我已在tag ...

中将ForeignKey声明为TaggedItem关系

1 个答案:

答案 0 :(得分:2)

您需要将标记字符串转换为实际的Tag对象。

for tag_name in tag_names:
    tag, created = Tag.objects.get_or_create(name=tag_name)
    tagged = TaggedItem(object=article, tag=tag)
tagged.save()