I have two tables on my Django database (SQLite), Field_Of_Research and Conference. Conference has three foreign keys associated to the primary key of Field_Of_Research. During the migrate command, I populate the database (reading from csv files), but when two conference with same foreign key value (for all three keys) are inserted, the UNIQUE constraint failed is diplayed. If I insert the confereces using the admin page, the database gives the same error. How can I solve this problem?
model.py
class Field_Of_Research (models.Model):
for_id = models.PositiveIntegerField(primary_key=True)
name = models.CharField(max_length=256)
def __str__(self):
return self.name
class Conference (models.Model):
conf_id = models.PositiveIntegerField(primary_key=True)
title = models.CharField(max_length=256)
primary_for = models.ForeignKey(to=Field_Of_Research, default=0, on_delete=models.SET_DEFAULT, related_name= 'primary_for')
secondary_for = models.ForeignKey(to=Field_Of_Research, default=0, on_delete=models.SET_DEFAULT, related_name= 'secondary_for')
third_for = models.ForeignKey(to=Field_Of_Research , default=0, on_delete=models.SET_DEFAULT, related_name= 'third_for')
def __str__(self):
return self.title
populate.py
with open('./server/api/database/files/fields_of_research.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=';')
for row in csv_reader:
f=Field_Of_Research.objects.get_or_create(
for_id = row[0],
name = row[1]
)
print(f'Fields of Research done.')
#Populates the conferences database
with open('./server/api/database/files/conferences.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=';')
for row in csv_reader:
print(row)
c=Conference.objects.get_or_create(
conf_id = row[0],
title = row[1],
primary_for = Field_Of_Research.objects.get(for_id=int(row[3])),
secondary_for = Field_Of_Research.objects.get(for_id=int(row[4])),
third_for = Field_Of_Research.objects.get(for_id=int(row[5])),
)
print(f'Conferences done.')
error
File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: api_conference.third_for_id