Version 5 (modified by 17 years ago) ( diff ) | ,
---|
Model API
This section explores the details of the GeoDjango Model API. Throughout this section, we'll be using the following geographic model of a Zip code as our example:
from django.contrib.gis.db import models class Zip(models.Model): code = models.CharField(maxlength=5) poly = models.PolygonField() objects = models.GeoManager()
Field Types
The following geometry-enabled fields are available:
PointField
LineStringField
PolygonField
MultiPointField
MultiLineStringField
MultiPolygonField
GeometryCollectionField
Each of these fields correspond with OpenGIS Simple Features.
Field Options
In addition to the regular field options available for Django models, Geographic-enabled models have the following additional options:
srid
- Sets the SRID (Spatial Reference System Identity) of geometry to the given value. Defaults to 4326 (WGS84). See Open GIS Consortium, Inc., OpenGIS Simple Feature Specification For SQL, Document 99-049 (May 5, 1999), at Ch. 2.3.8 (Geometry Values and Spatial Reference Systems, pg. 39).
index
- Defaults to True. Creates a GiST index for the given geometry. Update the index with the PostgreSQL command
VACUUM ANALYZE
(may take a while to execute depending on how large your geographic-enabled tables are). Please note that this is different from thedb_index
field option since geographic indexes are created in a different manner than regular indexes.
- Defaults to True. Creates a GiST index for the given geometry. Update the index with the PostgreSQL command
GeoManager
In order to conduct geographic queries, each geographic model requires GeoManager
. This manager allows for the proper SQL construction for geographic queries; thus, without it, all geographic filters will fail. It should also be noted that a GeoManager
will be required even if the model does not have a geographic field itself, i.e.,in the case of a ForeignKey
to a geographic model. For example, if we had an Address
model with a ForeignKey
to our Zip
geographic model:
from django.contrib.gis.db import models class Address(models.Model): num = models.IntegerField() street = models.CharField(maxlength=100) city = models.CharField(maxlength=100) state = models.USStateField() zip = models.ForeignKey(Zip) objects = models.GeoManager()
The geographic manager is needed to do spatial queries on related Zip objects, for example:
>>> qs = Address.objects.filter(zip__poly__contains='POINT(-104.590948 38.319914)')
GeoMixin
Update: The GeoMixin is no longer necessary for geographic models as of r6467. The mixin used to provide extra instance methods (discussed in the database api docs) for geographic models without subclassing (aka ModelInheritance) -- which is not yet functional in Django.