【问题标题】:Django Generic Relations not workingDjango通用关系不起作用
【发布时间】:2015-10-13 02:46:07
【问题描述】:

因此,在我的模型类之一中添加或删除 GenericRelation 之后,什么也没有发生。

我尝试进行迁移,但它告诉我没有检测到任何更改。所以肯定有问题,因为它应该命中数据库并尝试应用一些更改。

我按照 Django 示例进行操作,但无法建立关系。

class Person(models.Model):
    identity = models.CharField(max_length=13, verbose_name="ID")
    name = models.CharField(max_length=255, verbose_name="Name")
    board = GenericRelation('second_app.BoardMember') #Second Try

    def __unicode__(self):
        return self.identity

    class Meta:
        verbose_name = "Person"
        verbose_name_plural = "People"

class Student(Person):
    class Meta:
        proxy = True

class Parent(Person):
    class Meta:
        proxy = True

class Teacher(Person):
    board = GenericRelation('second_app.BoardMember') # first try
    class Meta:
        proxy = True

在另一个应用程序上,我有以下模型。

class BoardMember(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id', for_concrete_model=False)
    responsabilities = models.CharField(max_length=255)

起初我尝试在代理模型上设置通用关系。什么也没发生,然后我尝试将它设置在主 Person 类上。没有什么。这就是我在 shell 上测试关系所做的。

>>>from first_app.models import Teacher
>>>from second_app.models import BoardMember
>>>teacher = Teacher(identity='123456', name='Fermin Arellano')
>>>teacher.save()
>>>bm = Boardmember(content_object=teacher,responsabilities='Check stuff')
>>>bm.save()
>>>teacher.board.all()
[]

以下示例:https://docs.djangoproject.com/en/1.8/ref/contrib/contenttypes/#reverse-generic-relations

预期的结果应该是:[<Teacher: 123456>]

我做错了吗?任何地方都没有显示错误。数据已正确保存,Teacher 和 BoardMemer 对象均已在我的数据库中成功创建。

【问题讨论】:

    标签: python django


    【解决方案1】:

    我刚刚从 GenericForeignKey 声明中删除了 for_concrete_model=False。尽管在 Django 的文档中明确指出必须将其设置为 false 才能使用 ProxyModels。

    现在一切正常。

    编辑。

    我刚刚意识到问题仍然存在。经过进一步调查,我注意到为了使通用关系起作用,我需要保存 Person 模型的content_type_id,而不是代理模型。这就是为什么删除 for_concrete_model 参数有帮助的原因,因为这样我告诉 Django 使用父内容类型,并且它工作得很好。有趣的是,如果我执行以下操作,即使我有 Person 的 content_type_id,关系仍然有效。

    Teacher.objects.filter(board__isnull=False)
    

    这将返回董事会中的所有教师。

    这真是令人困惑,如果您能对这个烂摊子有所了解,我将非常感激。

    【讨论】:

    猜你喜欢
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 2017-07-18
    • 2016-03-05
    • 1970-01-01
    • 2018-03-05
    • 2016-05-08
    相关资源
    最近更新 更多