django.db.utils.IntegrityError: duplicate key value violates unique constraint “django_content_type_pkey”

前端 未结 5 1760
春和景丽
春和景丽 2020-12-31 00:43

Ran into a bit of a problem, i\'m getting the above error message when i run \'python manage.py syncdb\' I\'m working on a fairly old site. It\' running django

5条回答
  •  孤城傲影
    2020-12-31 01:18

    I received this error:

    django.db.utils.IntegrityError: duplicate key value violates unique constraint 
        "blahmodule_blahthing_blahstuff_id"
    DETAIL:  Key (blahstuff_id)=(1) already exists.
    

    A possible solution:

    • Try migrating the blahstuff relation in blahthing from a OneToOneField field to a ForeignKey

    An explanation with what I was using:

    I was using the Django RestFramework which was wired up through a ListCreateAPIView, and a ModelSerializer. For whatever reason the OneToOneField attaches a UNIQUE to one of the join tables blahmodule_blahthing_blahstuff_id, ( i'm not actually sure if its a join table, this is an assumption ), but whatever magic is happening in django switching to a ForeignKey with QuerySet returns, solved my issue.

    related:

    • What's the difference between django OneToOneField and ForeignKey?
    • https://www.postgresql.org/docs/11/ddl-constraints.html

    As far as the actual question above:

    schema :

    -- Table: public.django_content_type
    
    -- DROP TABLE public.django_content_type;
    
    CREATE TABLE public.django_content_type
    (
        id integer NOT NULL DEFAULT nextval('django_content_type_id_seq'::regclass),
        app_label character varying(100) COLLATE pg_catalog."default" NOT NULL,
        model character varying(100) COLLATE pg_catalog."default" NOT NULL,
        CONSTRAINT django_content_type_pkey PRIMARY KEY (id),
        CONSTRAINT django_content_type_app_label_model_76bd3d3b_uniq UNIQUE (app_label, model)
    
    )
    WITH (
        OIDS = FALSE
    )
    TABLESPACE pg_default;
    
    ALTER TABLE public.django_content_type
        OWNER to YOURUSER;
    

    Example rows:

    pk    app_label                model
    
    1   "your_app"           "your_app_model"
    2   "your_app"           "your_app_model"
    3   "blah_module"        "blahthing"
    4   "blah_module"        "blahstuff"
    

    The hash on django_content_type_app_label_model_76bd3d3b_uniq and the Primary Keys can get jumbled up if a migration fails mid process.

提交回复
热议问题