DB save() at the same time with a foreign key relation

Hello everyone,

I’m trying to make a db crud application. But somewhere I am getting this error. The code is too long that I think it would be better if I shared a few parts of it.

IntegrityError
Insert or Update on Table Violates Foreign Key

If there is no patient registered in the patient table(Epi_data), first I create a patient in the Epi_data model and save it to the db.

new_epidemic = Epi_data()
new_epidemic.patientid = _tempPatientID
......
new_epidemic.save()

new_sample = Samples()
new_item_details['patientid_id'] = _tempPatientID
new_sample.__dict__.update(new_item_details)
new_sample.save() // It gives the error here.

Then, thinking that this patient’s id is in the Epi_data table now,so I can create sample data of the patient that matches patient’s id(_tempPatientID). I want it to do these two save() operations by pressing a single button on the screen at the same time. But it gives an IntegrityError saying that the patientid value I saved in the Epi_data() model is not in the Samples() model. What am I doing wrong? Thank you in advance.

models.py

class Epi_data(models.Model):

    patientid = models.CharField(max_length=256, unique=True)
    bday = models.DateField(null=True, blank=True)
    age = models.IntegerField(null=True, blank=True)
    gender = models.CharField(max_length=10, null=True, blank=True)
    born_country = models.CharField(max_length=64, null=True, blank=True)
    residence = models.CharField(max_length=128, null=True, blank=True)
    postcode = models.CharField(max_length=8, null=True, blank=True)
    epi_data_hospitals = models.ForeignKey(Hospitals, related_name='epi_data_hospitals', on_delete=models.CASCADE)

class Samples(models.Model):

    p_id_s = models.CharField(max_length=128, null=True)
    projects = models.ForeignKey(Projects, related_name='sample_projects', on_delete=models.CASCADE)
    hospitals = models.ForeignKey(Hospitals, related_name='sample_hospitals', on_delete=models.CASCADE)
    source_samples = models.ForeignKey(SourceSamples, related_name='sample_source', on_delete=models.CASCADE)
    patientid = models.ForeignKey(Epi_data, related_name='sample_patientid', on_delete=models.CASCADE)

We’ll need to see more of that view. There’s too much information missing from the snippet you’ve provided to allow for an appropriate diagnosis.

There is one area that I would question - a ForeignKey is supposed to reference the Primary Key of the referenced table. Unless you’re doing something other than what’s shown here, you’re not doing that in your code. (Epi_data.patientid is not defined as the primary key.)