Saturday, January 30, 2021

IntegrityError on a foreign key constraint

Hi, I'm having a really incomprehensible error currently. We are working with three models here, "DataImport", "Contact" and "Dataset", the DataImport model import data from a file to a Dataset object, the data is imported as a Contact object , the DataImport model have a foreign key to the Dataset model. This is how the app works:

- a user upload a file
- we convert the content of the file to a TablibDataset or TablibDatabook, these are tablib (python package) classes, don't worry too much about this, tablib have their own Dataset and I have my own, that's why I import the tablib classes with aliases
- if the loaded data is a TablibDataset, the import start and create contacts from the loaded data (this works)
- if the loaded_data is a TablibDatabook, the databook is split into multiple sheet (yes I'm working with excel files) and new Dataset (my model)  and DataImport objects are created to handle the import for each  sheet (here is the issue)

All import are done as async task using the django_q package
The issue I have is that, when I create a new dataset, start the import and try to add a new contact I get this:
```
insert or update on table "datasets_contact" violates foreign key constraint "datasets_contact_dataset_id_9dda7f76_fk_datasets_dataset_id"
DETAIL:  Key (dataset_id)=(39) is not present in table "datasets_dataset".
```
It seems like the dataset is not save in db that's why I'm getting this error when I try to create a new contact, but I'm creating my Dataset object with Dataset.objects.create(), I don't understand the problem.

The code for all this is a bit long, so here is a gist with all the necessary code 
https://gist.github.com/Tobi-De/411ee7b7fc988864869c8d7ad93ab34f

The method that create the Dataset and DataImpot objects is the class method "create_import_from_databook"

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/dbfc0761-347d-47a5-9689-9886ce1e37fcn%40googlegroups.com.

No comments:

Post a Comment