Django / postgresql - model with only foreign keys

Viewed 226

I have a model which looks like this:

class InputTypeMap(models.Model):
    input_type = models.ForeignKey(InputType, on_delete=models.CASCADE)
    training = models.ForeignKey(Training, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    gender = models.ForeignKey(Gender, on_delete=models.CASCADE)

When I try to create instances of this model with:

InputTypeMap.objects.create(input_type=input_type,
                            training=training,
                            gender=gender,
                            category=category)

I get an exception

Traceback (most recent call last):
  File "/home/hove/sleipner/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.NotNullViolation: null value in column "id" violates not-null constraint
DETAIL:  Failing row contains (null, Maintenance, Female, MareGielding, No).

From the error message it seems to me that a ID key for the new entry is not generated.

This code has worked as I expected for quite some time, but has "suddenly" started to fail locally - probably after a apt get upgrade. When I run the same code with sqlite or Postgres-10.14 things continue to work as before. It is not clear to me whether this is a bug in my code (most probable ...), Django or Postgres. I am using Django version 3.1.2

I have version 9.6 of the Postgres server

2 Answers

most probably, that is a primary_key problem, in my case i added to my model something like:

person_id = models.AutoField(primary_key=True)

adapt my views to it, and it solved it,

Related