Opened 6 years ago

Closed 6 years ago

#28952 closed Bug (worksforme)

inspectdb generates primary_key with null=True

Reported by: Victor Fernandez Martinez Owned by: nobody
Component: Core (Management commands) Version: 1.11
Severity: Normal Keywords: inspectdb primary_key null
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I have a PostgreSQL 9.6 table that looks like this:

CREATE TABLE admin_item_permissions
(
  id bigint NOT NULL DEFAULT nextval('next_unique_id_seq'::regclass),
  admin_id bigint,
  item_id bigint,
  permissions integer,
  CONSTRAINT admin_item_permissions_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);

CREATE UNIQUE INDEX admin_perms_item_id_admin_id
  ON admin_item_permissions
  USING btree
  (admin_id, item_id);

When I run inspectdb, it generates the following model:

class AdminItemPermissions(models.Model):
    id = models.BigIntegerField(primary_key=True, blank=True, null=True)
    admin_id = models.BigIntegerField(blank=True, null=True)
    item_id = models.BigIntegerField(blank=True, null=True)
    permissions = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        unique_together = (('admin_id', 'item_id'),)

The "id" field generated by inspectdb contains "null=True", even though it's a primary key and the "id" column explicitly has "NOT NULL". I would expect it not to add "null=True" instead, or to add "null=False".

This also causes creation of a test database to fail when trying to run unit tests, with the following error message:

ERRORS:
common.AdminItemPermissions.id: (fields.E007) Primary keys must not have null=True.
	HINT: Set null=False on the field, or remove primary_key=True argument.

Change History (1)

comment:1 by Claude Paroz, 6 years ago

Resolution: worksforme
Status: newclosed

I'm unable to reproduce your issue. This is what I'm getting on PostgreSQL 9.6, Django 1.11 (also tested on Django 2.0):

class AdminItemPermissions(models.Model):
    id = models.BigAutoField(primary_key=True)
    admin_id = models.BigIntegerField(blank=True, null=True)
    item_id = models.BigIntegerField(blank=True, null=True)
    permissions = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'admin_item_permissions'
        unique_together = (('admin_id', 'item_id'),)
Note: See TracTickets for help on using tickets.
Back to Top