Search code examples
pythondjangopostgresqldjango-modelsdjango-south

Django datetime primary key doesn't constrain unique


So, here's my model:

class MyModel(models.Model):
    timestamp = models.DateTimeField(primary_key=True)
    fielda = models.TextField()

When I call syncdb, django doesn't add a constraint to postgresql for timestamp to be unique, even though it gives it the primary key constraint.

If I change timestamp to just unique=True, django creates the unique constraint. However, if I combine unique=True and primary_key=True, django doesn't create the unique constraint.

My info:

  • django-south v1.8
  • django 1.4
  • python 2.7
  • postgresql 9.1

Edit:

If I save a model with the same exact timestamp twice in two different runs (not the same process), it doesn't raise and IntegrityError like it should. But when it creates the unique constraint and no primary key, it does with the same code.

Edit 2:

This is the code that runs when I have CONSTRAINT "MyModel_pkey" PRIMARY KEY ("timestamp") in postgresql from just having timestamp = models.DateTimeField(primary_key=True)

timestamp = datetime.datetime(2013, 7, 31, 0, 0, 0).replace(tzinfo=utc)
print timestamp # prints 2013-07-31 00:00:00+00:00
row = MyModel(timestamp=timestamp, fielda='test')
row.save()

When run twice in a row, it doesn't raise an IntegrityError. However, with the unique=True and not primary_key=True, it does raise an IntegrityError.


Solution

  • Ricola3D linked me to the same question (that's answered) that explains my problem.

    Answered Question