I upgraded from Django 1.11 to Django 2.0 and my tests started failing. I have 7 TestCase
classes and all use the setUpTestData
provided by Django. When I run them all together one of them fails to set up because of an psycopg2.IntegrityError: duplicate key value violates unique constraint "doctors_doctor_pkey"
.
When I run one of those TestCase
classes alone it works fine. It seems like they're influencing each other in some way, but it's strange that it would fail after upgrading to Django 2.0. I've also noticed it's not at the create()
it's at the save()
.
In the setup for the dashboards
app I have some creation data:
cls.d1 = doctor_models.Doctor.objects.create(email="johndoe@example.com", name="John Doe",
specialization=cls.s1, premium=True,
premium_price=4310, consultation_price=341)
...
cls.b1 = doctor_models.DoctorBooking.objects.create(clinic=cls.c1, doctor=cls.d1,
status=2, premium_booking=True,
patient_name="example",
patient_phone_number="+9747721234",
confirmed_date=datetime.strptime(
"16 Jun 2017 14:22:26:000 +0300",
receive_format),
handled_on=datetime.strptime(
"17 Jun 2017 14:22:26:000 +0300",
receive_format))
The second line from above would call it's save()
function that would call save()
on cls.d1
def save(self, *args, **kwargs):
if self.doctor.premium:
self.premium_booking = True
else:
self.premium_booking = False
super(DoctorBooking, self).save(*args, **kwargs)
self.doctor.save() # <- here it raises an IntegrityError
This is the simplest code I could extract, but this happens all over for different classes.
To reiterate this gives me the following.
psycopg2.IntegrityError: duplicate key value violates unique constraint "doctors_doctor_pkey"
DETAIL: Key (id)=(7) already exists.
I'm not even sure why this is happening. When you create an object shouldn't psycopg2
take care of auto-incrementing the pk
? From what I can gather the database doesn't have any issues, when I add a breakpoint before the .save()
and check the Database a doctor with the same data and pk
is already in the database. So I'm guessing it's assuming that these two objects are different... but I'm calling create then save NOT create twice.
EDIT: Solved in the comments :D