IntegrityError when saving a new model instance
washougal opened this issue · 1 comments
I'm using django-rest-framework, and have a test that requires a specific primary key to be specified from a get request, and another test that takes a post request and saves it. A simplified version of what I have:
#models.py
class Equipment(models.Model):
equipment_name = models.TextField()
#tests.py
class TestAPI(TestCase):
def setUp(self):
self.equipment = mommy.make(
'App.Equipment',
equipment_name='Test Equipment',
id=1
)
def test_post(self):
response = self.client.post(url, {'equipment_name': 'Another piece of equipment'}, format='json')
When setting the primary key in the mommy make method, I get:
IntegrityError: duplicate key value violates unique constraint "App_equipment_pkey" DETAIL: Key (id)=(1) already exists.
Removing the id attribute resolves the problem. Is there a way to explicitly set the primary key for one mommy object, and just rely on django figuring out the primary keys on the next object that's created? Right now I have to split tests into two different classes that could be combined into one.
@washougal isn't there any lost project's or app's fixture you're defining as initial data? Because the exception being raised (IntegrityError
) means the database already has an entry with the id 1. Take a look if there aren't other piece of codes being executed before your test.
About model mommy, it does support id assignment:
In [1]: Dataset.objects.latest('id').id
Out[1]: 6
In [2]: from model_mommy import mommy
In [3]: ds_42 = mommy.make(Dataset, id=42)
In [4]: ds_42.refresh_from_db()
In [5]: ds_42.id
Out[5]: 42