Django:通用外键dumpdata:无法解析依赖项

Bab*_*abu 5 generics django foreign-key-relationship natural-key dumpdata

我使用通用外键将不同的配置文件与我Users继承的模型相关联auth.User.dumpdata虽然通过了--natural选项,但我无法做到.它说,

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

根据文档,据说我们需要实现natural_key方法来获取和闪存涉及通用关系的灯具.我怎么能用这里展示的模型做到这一点?

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')
Run Code Online (Sandbox Code Playgroud)

使用Django 1.4.3和Postrgres.

mgi*_*nbr 7

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

经过一些搜索后,我发现当模型之间存在循环依赖关系(包括具有自引用的模型)时会出现此问题.正如您的更新代码所示,模型中有一个自引用Users,因此问题就在于此.这个错误是在Django 1.3中引入的,尽管已经修复,但在稳定版本中仍然无法使用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")
Run Code Online (Sandbox Code Playgroud)