3

我使用通用外键与从auth.User继承了我Users模型涉及不同的配置文件。我不能做dumpdata虽与--natural选项传递。它说,Django的:通用外键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。

回答

6

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

经过一番搜索,我发现这个问题时,有模型之间循环依赖(包括自参考模型)出现。如更新后的代码所示,Users模型中有一个自我参考,所以这就是问题所在。此错误是在Django 1.3引入,尽管是already fixed,它仍然无法AFAIK的稳定版本(测试可达1.4.3)。然而,在测试版本(1.5b2)中,你的代码工作正常。

如果使用的是测试版(或降级到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") 
+0

*我发现当模型(包括具有自引用的模型)*之间存在循环依赖关系时,会出现此问题。谢谢(你的)信息。其实我有一个自我参考的领域。对不起,第一次没有添加(现在检查编辑)。当我删除它时,我可以获得转储。但无论如何我需要这个领域。那可能吗?或者我必须创建另一个模型来保持这种兴趣? – Babu

+1

@Babu就是这样!检查我更新的答案。你的代码在1.2.5和1.5b2(这个bug已经被修复)中工作正常,但是在1.4中没有(我假设在1.3中)。 – mgibsonbr

+0

感谢您的详细解答和多版本测试结果。 :)我会去创建另一个模型。这很奇怪,可惜它在1.4中不固定。 – Babu