【问题标题】:Django indirect generic relationDjango 间接泛型关系
【发布时间】:2012-03-20 10:46:38
【问题描述】:

我一直在尝试为我的应用程序实现一个标记系统,其中每种内容类型只允许使用某些标记。

我尝试在 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?

【问题讨论】:

    标签: python django tags generic-relations


    【解决方案1】:

    错误在这里:

    ta.content_object = ta.tag.appliable_to
    

    这里的 ta.content_object 不是 Company 对象而是 ContentType。正确的代码应该是:

    ta.content_object = Company.objects.get(id=1).id
    

    另外,你不必直接设置 ta.object_id,它是由 GenericForeignKey 字段完成的

    【讨论】:

    • 遗憾的是,这似乎不起作用。您的代码呈现 AttributeError: 'int' object has no attribute '_state' 。我删除了最后一个 id ,错误是 AttributeError: 'Company' object has no attribute 'model'
    • 最后,我发现,除了id,你的解决方案是正确的,我的代码在__unicode____unicode__ 方法上被破坏了TagAttribution
    猜你喜欢
    • 2011-09-29
    • 2011-01-17
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 2012-09-12
    相关资源
    最近更新 更多