简体   繁体   中英

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 .

Maybe the example from the docs can bring some light into your question

Technically, a primary key constraint is simply a combination of a unique constraint and a not-null constraint. So, the following two table definitions accept the same data:

 CREATE TABLE products ( product_no integer UNIQUE NOT NULL, name text, price numeric ); CREATE TABLE products ( product_no integer PRIMARY KEY, name text, price numeric ); 

[...] A primary key indicates that a column or group of columns can be used as a unique identifier for rows in the table [...] Adding a primary key will automatically create a unique btree index on the column or group of columns used in the primary key. [...]

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

Answered Question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM