[Answered ]-IntegrityError at. insert or update on table violates foreign key constraint

2👍

 try:
     club = Club.objects.get(club_name=str(row[1]))
     club.save() # <-- You don't need to save. You haven't changed anything on the club.
 except:
     club = Club.objects.get(club_name="No Club")
     club.save() # <-- You don't need to save. You haven't changed anything on the club.

And model ids declared by django are numeric, so don’t use thing = str(club.id).

Also, using the attribute pk is preferable over id because pk will always point to the real primary key name. This means if you ever change the primary key of your models, you won’t need to change all the id accesses in your code.

You need to change profile.club=thing to profile.club.add(club.pk) because your club attribute is declared as a models.ManyToManyField(Club) which is a sequence of Club objects, not a single one.

Or… you may change it and use a models.ForeignKey(Club) which is more coherent with the attribute name (club) (do this only in case that your users can only be members of one club at the same time)

0👍

When this error happens, what is tends to be related to is that you made a mistake when creating one or more foreign key fields for your model.

First of all make sure your model foreign key fields are pointing to the right table.

For instance, if you have the following model:

class ModelA(models.Model):
    ...
    model_b = models.ForeignKey(ModelB, ...)
    model_c = models.ForeignKey(ModelB, ...) # <-- wrong model in foreign key
    ...

You might be accidentally using ModelB on both foreign keys, where you should instead be using ModelC:

class ModelA(models.Model):
    ...
    model_b = models.ForeignKey(ModelB, ...)
    model_c = models.ForeignKey(ModelC, ...) # <-- correct model in foreign key
    ...

Otherwise, when you try to create a new model instance of model A:

>>> ModelA.objects.create(model_b_id=<int>, model_c_id=<int>)

Since model_c_id is setting a value for an id for ModelB, this may throw an error because you are looking for a foreign key that exists in ModelC table, and that does not necessarely exists for the ModelB table.

Leave a comment