RobinReborn
RobinReborn

Reputation: 451

Django subclass model gives "duplicate key value violates unique constraint" on save

I have a class with many fields:

class Parent(models.Model):
    id = models.AutoField(primary_key=True)
    ... many more fields

and I create a subclass

class Child(Parent):
    other_field = models.CharField(max_length=512, blank=True, null=True)
    date_featured = models.DateField()

After I migrate and create a Child object in the admin I get

duplicate key value violates unique constraint "parent_pkey"
DETAIL:  Key (id)=(5) already exists.

I've seen some similar questions that suggest that you modify the database but I can't easily do that. Do I need to change the id of the subclass?

Upvotes: 1

Views: 1439

Answers (2)

RobinReborn
RobinReborn

Reputation: 451

I was able to fix this by removing id from the parent model. I think the issue was that the child's id started at 0 and that violated that uniqueness of the parent's pk. Using Django's built in primary key system works.

Upvotes: 1

Catalin
Catalin

Reputation: 135

Using a SubClass which usually it is called "Table inheritance" under the hood it creates a OneToOne relationship between the Child and the Parent.

Now This can be good or bad depending how you intend to use it:

God:

  • you handle the Child and the Parent Data through the child only without you to micromanage what data gets saved into the Parent Model and what data gets saved into the Child Model (especially if you use a ModelForm or even a ModelSerializer)

Bad:

  • OneToOne relationship it is under Unique constraint.

This means you can only have one Parent associated with one Child at a time. Ex: a OneToOne relation between Parent(with ID 13) and the Child(with the ID 25) has to be unique and no other Child can have another OneToOne relation with the Parent(with ID 13)

As I said this is Bad or Good...

A User model can be assigned as a Parent for Profile(User) which implicitly ensures Uniqueness (no user will have more than One Profile) and You can manage the entire CRUD through the Profile Model Directly.

But if you need to inherit from Parent class in order to create multiple Child class instances...then The ForeignKey is the solution. (OneToMany).

Or perhaps you already know that and in fact..somehow one of your Child instances is not Dumping/removing the Parent relation fast enough so that it could be taken by another Child instance AFTER...

Upvotes: 0

Related Questions