geometry column contains null values

940 views Asked by At

So I am trying to add a point field to a model in django which looks like this:

class Location(models.Model):
    lat = models.FloatField(blank=True, null=True)
    lng = models.FloatField(blank=True,null=True)
    geometry = models.PointField(srid=4326,default='POINT(0.0,0.0)')
    objects = models.GeoManager()

I already have database with lots of locations with the lat lng coordinates but they don't need a point field. I am getting this error django.db.utils.IntegrityError: column "geometry" contains null values

I set the default but it still gives me that error when I run 'python manage.py migrate' How can I fix this?

1

There are 1 answers

2
sedavidw On BEST ANSWER

The default does not change old rows in the database (that existed before the migration). You should set the the geometry field to be nullable and then migrate. Once migrated you can either fill in the null values with the default and remove null=True or leave as is

UPDATE

Based on this post it seems very possible that PointField cannot be null (even if it's specified to be which really grinds my gears...). GIVEN that your model does not need to change but it doesn't look like django can handle this super well for you.

I see two options (better ones might exist)

  1. Do the data migration on the actual table yourself (I THINK with most databases when you add in a new column you can set a default there and it will populate that for you)
  2. Create a new model which is essentially the same with the new columns, copy the data over, delete the old model and columns.

Neither of these seem ideal but the googles have not yet shown me a better way