我使用通用外键将不同的配置文件与我的 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/