Django : Generic Foreign key dumpdata: Can't resolve dependencies

标签 django generics foreign-key-relationship natural-key dumpdata

我使用通用外键将不同的配置文件与我的 Users 模型相关联,该模型继承自 auth.User。尽管传递了 --natural 选项,但我无法执行 dumpdata 。它说,

错误:无法解析序列化应用列表中 myproject.AdminProfile、myproject.TeacherProfile、myproject.Users 的依赖项。

根据documentation ,据说我们需要实现natural_key methods拍摄和闪光灯具这涉及到通用关系。我怎样才能用这里展示的模型做到这一点?

class Users(User):
    location = models.TextField('Location', blank=True)
    created_by = models.ForeignKey('self', null=True, blank=True, related_name='created_by_user')

    # Generic foreign key setup to hold the extra attributes
    profile_contenttype = models.ForeignKey(ContentType, null=True, blank=True)
    profile_object_id = models.PositiveIntegerField('Extra ID', null=True, blank=True)
    profile_object = generic.GenericForeignKey('profile_contenttype', 'profile_object_id')


class AdminProfile(models.Model):
    organization = models.CharField('Organization', max_length=100)

    # profile reverse relation to get the user
    users_link = generic.GenericRelation('Users', content_type_field='profile_contenttype',
                                         object_id_field='profile_object_id')

class TeacherProfile(models.Model):
    designation = models.CharField('Designation', max_length=100)

    # profile reverse to get the user
    users_link = generic.GenericRelation('Users', content_type_field='profile_contenttype',
                                         object_id_field='profile_object_id')

使用 Django 1.4.3 和 Postrgres。

最佳答案

您的问题似乎与缺少自然键方法无关。我使用 SQLite 在 Django 1.4 和 1.2.5 上按原样测试了您的[原始]代码,并且能够使用自然键转储数据,没有错误。

经过一番搜索,我发现当模型之间(包括具有自引用的模型)之间存在循环依赖时,就会出现此问题。正如更新的代码所示,Users 模型中有一个自引用,所以这就是问题所在。这个错误是在 Django 1.3 中引入的,尽管是 already fixed ,据我所知,它在稳定版本中仍然不可用(测试到 1.4.3)。然而,在测试版(1.5b2)中,您的代码运行良好。

如果使用 beta 版本(或降级到 1.2)不是一个选择,那么您唯一的解决方案可能就是创建另一个模型。像这样的东西:

class CreatedBy(models.Model):
    creator = models.ForeignKey(Users, related_name="created_by_user")
    created = models.ForeignKey(Users, unique=True, related_name="created_by")

关于 Django : Generic Foreign key dumpdata: Can't resolve dependencies,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14021703/

相关文章:

MySQL Laravel 使外键唯一

python - 基于 Django 的网站的好方法,如果需要安装先决条件

django - 将外键下拉列表替换为带有添加/编辑图标的文本框 - Django

c# - 使用泛型属性调用重载方法会调用错误的重载

TypeScript:如何在不指定模板参数的情况下使用模板化类型?

java - 使用 T 型删除、搜索和返回位置

database - 规范化 - 重复外键

python - Django:从父表到子表的外键

python - ValueError 精确查找的 QuerySet 值必须限制为使用 django View 上的切片的一个结果

python - 定位 libmysqlclient_r.so.16 issue