1

I am receiving this error when attempting to migrate:

"return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: unit_manifests.product_name_id"

This is in reference to the product_name field in the model below.

1) Why do I need to set a default value for a foreign key field?

2) I initially ran without default = none, blank = true, null = true. I have now run makemigrations again but when I migrate I still get the error, I believe it is attempting to run an old migrations first. How can I get around this?

MODELS.PY

class Manifests(models.Model):

    reference = models.ForeignKey(Orders)
    cases = models.IntegerField()
    product_name = models.ForeignKey(Products, default=None, blank=True, null=True)
    count = models.IntegerField()
    CNF = models.DecimalField(max_digits=11, decimal_places=2, default=None, blank=True, null=True)
    FOB = models.DecimalField(max_digits=11, decimal_places=2, default=None, blank=True, null=True)

    def __str__(self):
        return self.description
Rajan Sharma
  • 2,211
  • 3
  • 21
  • 33
GXM100
  • 417
  • 6
  • 20
  • delete your old migrations and migrate again. You probably need a default because you already have objects and they are now not properly referenced with the fk. – hansTheFranz Jul 11 '19 at 12:29
  • @hansTheFranz makes sense...but how do I go about deleting the migrations? Delete the files from the folder structure or is there a command I can use to do this? – GXM100 Jul 11 '19 at 12:32
  • Each app in your project has a folder and if you have models in it you also will have a folder called "migrations". just delete the last migration and hit `./manage.py migrate yourAppName 00XX` in your terminal where XX is the number of the last migration. I wrote this answer for another migration problem but the solution is the same. https://stackoverflow.com/questions/44182633/django-migration-dependencies-reference-nonexistent-parent-node/44182969#44182969 – hansTheFranz Jul 11 '19 at 13:24

1 Answers1

0

Django migrations works like this.

First you run makemigrations which will create a file based on changes from the last file generated from running makemigrations.

Then you run migrate which will push the changes in the migrations folder which are not yet registered in the database in table 'django_migrations'. The migration file names are important because django uses it to identify the migration.

If you want to fake a migration, you can manually create a database instance in the migrations table with the migrations file you want to fake.

Lets say the migration file is called '0002_auto_20190212_1240.py', then you insert a row in the 'django_migrations' table with app=[app_name], name=0002_auto_20190212_1240 and applied=[+1 second after last instance].