pythondjangogeodjango

Django where to store model-level variables


So I have my model:

from django.db import models

x_default_coordinate = 0
y_default_coordinate = 0

class MyModel(models.Model):
  location1 = gis_models.PointField(
        srid=4326, default=Point(x_default_coordinate, y_default_coordinate)
    )
  location2 = gis_models.PointField(
        srid=4326, default=Point(x_default_coordinate, y_default_coordinate)
    )

Where would be an appropriate place to store the default coordinates? Currently I have them as shown, but that doesn't seem right.


Solution

  • I'm not familiar with the Point object and whatever package you are using, so I'm going to answer your question assuming that Point is a mutable object.

    The docs for Field.default:

    The default can’t be a mutable object (model instance, list, set, etc.), as a reference to the same instance of that object would be used as the default value in all new model instances. Instead, wrap the desired default in a callable.

    To avoid accidentally mutating the default object, you should wrap the default in a callable:

    DEFAULT_X = 0
    DEFAULT_Y = 0
    
    def get_default_point():
        return Point(DEFAULT_X, DEFAULT_Y)
    
    
    class MyModel(models.Model):
        location1 = gis_models.PointField(srid=4326, default=get_default_point)
        ....