GenericForeignKey 违规仅当给定用户模型时,Postgres

use*_*182 3 django django-models

我有一个活动应用程序来记录用户或任何活动操作。因此,为了实现这一点,我必须在我的模型上使用 GenericForeignKeys,因为许多模型都可以执行操作。

这是我的模型:

class Activity(models.Model):
    actor_content_type = models.ForeignKey(
        ContentType, related_name='actor'
    )
    actor_object_id = models.CharField(max_length=500)
    actor = generic.GenericForeignKey(
        ct_field='actor_content_type', fk_field='actor_object_id'
    )
    verb = models.CharField(max_length=50)
Run Code Online (Sandbox Code Playgroud)

我可以很好地创建记录,将任何模型实例传递给“actor”,但是当我传递 django User 模型实例时,出现以下错误:

self = <django.db.backends.postgresql_psycopg2.base.DatabaseWrapper object at 0x2d3bfd0>

    def _commit(self):
        if self.connection is not None:
            try:
>               return self.connection.commit()
E               IntegrityError: insert or update on table "auth_permission" violates foreign key constraint "content_type_id_refs_id_d043b34a"
E               DETAIL:  Key (content_type_id)=(3) is not present in table "django_content_type".

/usr/local/lib/python2.7/dist-packages/Django-1.5.10-py2.7.egg/django/db/backends/postgresql_psycopg2/base.py:240: IntegrityError
>           
Run Code Online (Sandbox Code Playgroud)

谁能弄清楚为什么会这样?

小智 5

在您的设置模块中,更改“INSTALLED_APPS”变量的顺序,使“django.contrib.auth”低于“django.contrib.contenttypes”,例如:

从:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    ...etc
)
Run Code Online (Sandbox Code Playgroud)

到:

INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.auth',
    ...etc
)
Run Code Online (Sandbox Code Playgroud)