BiAiB
BiAiB

Reputation: 14132

Why django inspectdb skips some ids?

I was running inspectdb on my schema. At first, the defitions are very correct like these:

class Diagnosis(models.Model):
    id = models.BigIntegerField(primary_key=True)
    code = models.CharField(max_length=255)
    starting_node = models.ForeignKey('Node', models.DO_NOTHING, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'diagnosis'


class DiagnosisTranslation(models.Model):
    id = models.IntegerField(primary_key=True)
    language = models.CharField(max_length=10)
    title = models.CharField(max_length=255, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    diagnosis = models.ForeignKey(Diagnosis, models.DO_NOTHING, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'diagnosis_translation'

Then, I added sequences and default values (postgresql) for Ids:

CREATE SEQUENCE diagnosis_id_seq START WITH 100000 INCREMENT BY 1;
ALTER TABLE diagnosis ALTER COLUMN id SET default nextval('diagnosis_id_seq');

CREATE SEQUENCE diagnosis_translation_id_seq START WITH 100000 INCREMENT BY 1;
ALTER TABLE diagnosis_translation ALTER COLUMN id SET default nextval('diagnosis_translation_id_seq');

I reran again python manage.py inspect, and the outcome changes correctly for diagnosis, but not for the other table, it lacks the id attribute now:

class Diagnosis(models.Model):
    id = models.BigAutoField(primary_key=True)
    code = models.CharField(max_length=255)
    starting_node = models.ForeignKey('Node', models.DO_NOTHING, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'diagnosis'

class DiagnosisTranslation(models.Model):
    # Where's the ID ??
    language = models.CharField(max_length=10)
    title = models.CharField(max_length=255, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    diagnosis = models.ForeignKey(Diagnosis, models.DO_NOTHING, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'diagnosis_translation'

Why does Django omits the Ids for some tables and not others ? Especially why does it only happens when I make the id fields autoincrement ?

Upvotes: 2

Views: 248

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476803

If you do not explicitly define a primary key. Django defines a primitive key automatically [Django-doc]. So in that case a field is implicitly added:

id = models.AutoField(primary_key=True)

Django will thus omit specifying the primary key explicitly given:

  1. the primary key has as name id; and
  2. the primary key has as type IntegerField [Django-doc] (an AutoField [Django-doc] is an IntegerField that automatically increments according to available IDs.

Upvotes: 2

Related Questions