def forwards(self, orm): GeoManager().contribute_to_class(orm.Shape, "objects") GeoManager().contribute_to_class(orm.ShapePoint, "objects") for shape in orm.Shape.objects.all(): if shape.points.count() >= 2: points = orm.ShapePoint.objects.filter( shape=shape).order_by('sequence').values_list('point', flat=True) ls = 'LINESTRING (' + ', '.join( ['%s %s' % pt.coords for pt in points]) + ')' shape.geometry = ls shape.save()
def forwards(self, orm): GeoManager().contribute_to_class(orm.Route, "objects") GeoManager().contribute_to_class(orm.Trip, "objects") for route in orm.Route.objects.all(): trips = orm.Trip.objects.filter(route=route).exclude(geometry=None) if trips.exists(): ls = [] for trip in trips: ls.append('(' + ', '.join( ['%s %s' % pt for pt in trip.geometry.coords]) + ')') mls = 'MULTILINESTRING(' + ','.join(ls) + ')' route.geometry = mls route.save()
class Place(models.Model): name = models.CharField(max_length=200, db_index=True, verbose_name="ascii name") alt_names = models.ManyToManyField(swapper.get_model_name('cities', 'AlternativeName')) perimeter = models.MultiPolygonField(null=True, blank=True) objects = GeoManager() class Meta: abstract = True @property def hierarchy(self): """Get hierarchy, root first""" lst = self.parent.hierarchy if self.parent else [] lst.append(self) return lst def get_absolute_url(self): return "/".join([place.slug for place in self.hierarchy]) def __str__(self): return force_text(self.name) def save(self, *args, **kwargs): if hasattr(self, 'clean'): self.clean() super(Place, self).save(*args, **kwargs)
class PaintingFeature(Feature, BuiltFormFeature): """ Represents a feature that can be "painted" in the API TODO replace this by means of a Behavior """ objects = GeoManager() dev_pct = models.DecimalField(max_digits=8, decimal_places=4, default=1.0000) density_pct = models.DecimalField(max_digits=8, decimal_places=4, default=1.0000) gross_net_pct = models.DecimalField(max_digits=8, decimal_places=4, default=1.0000) clear_flag = models.BooleanField(default=False) dirty_flag = models.BooleanField(default=False) developable_proportion = models.DecimalField(max_digits=8, decimal_places=4, default=1) acres_developable = models.DecimalField(max_digits=14, decimal_places=4, default=0) class Meta(object): abstract = True app_label = 'main'
class Checkin(models.Model): seller_name = models.CharField(max_length=255, verbose_name='Your name') point = PointField(blank=True) time = models.DateTimeField(auto_now=True) expiry = models.DateTimeField() expiry_offset = models.IntegerField(verbose_name='For how long?', default=3600, choices=( (3600, u'1 Hour'), (7200, u'2 Hours'), (10800, u'3 Hours'), (14400, u'4 Hours'), )) items = models.ManyToManyField(Item) notes = models.TextField( help_text='Any additional information you would like to share.') objects = GeoManager() class Meta: ordering = ('-time', ) def __unicode__(self): return self.seller_name def save(self, *args, **kwargs): self.expiry = datetime.now() + timedelta(0, self.expiry_offset) super(Checkin, self).save(*args, **kwargs)
class Incidence(models.Model): name = models.CharField(max_length=255) location = gis_models.PointField(srid=4326) objects = GeoManager() def __str__(self): return self.name
class Airport(models.Model): name = models.CharField(_("name"), max_length=100) iata = models.CharField(_("IATA/FAA code"), blank=True, max_length=3, validators=[MinLengthValidator(3)], db_index=True, primary_key=True ) icao = models.CharField(_("ICAO code"), blank=True, max_length=4, validators=[MinLengthValidator(4)] ) altitude = models.FloatField(_("altitude"), default=0) location = models.PointField(_("location")) country = models.ForeignKey('cities.Country', on_delete=models.DO_NOTHING, null=True) city = models.ForeignKey('cities.City', on_delete=models.DO_NOTHING, null=True) objects = GeoManager() class Meta: # pylint: disable=C1001 ordering = ['iata'] def __str__(self): return force_text(self.name)
class LogEntryBase(models.Model): """ Abstract base model for Geotrack log entry. """ # Hard-coding this as an integer field for simplicity for the moment. unit_id = models.PositiveIntegerField(db_index=True) timestamp = models.DateTimeField( db_index=True, help_text='Date/time when the measurement was taken.') location = LocationField() added = models.DateTimeField( default=datetime.now, help_text='When the log entry arrived in the system') objects = GeoManager() class Meta: abstract = True ordering = 'timestamp', def save(self, **kwargs): super(LogEntryBase, self).save(**kwargs) self.update_last_known_position() def update_last_known_position(self): data = dict(timestamp=self.timestamp, location=self.location) last_pos, created = LastKnownPosition.objects.get_or_create( unit_id=self.unit_id, defaults=data) if not created and last_pos.timestamp < self.timestamp: for name, val in data.items(): setattr(last_pos, name, val) last_pos.save()
class StoreStock(models.Model): store = models.ForeignKey( 'stores.Store', verbose_name=_("Store"), related_name='stock' ) product = models.ForeignKey( 'catalogue.Product', verbose_name=_("Product"), related_name="store_stock" ) # Stock level information num_in_stock = models.PositiveIntegerField( _("Number in stock"), default=0, blank=True, null=True ) # The amount of stock allocated in store but not fed back to the master num_allocated = models.IntegerField( _("Number allocated"), default=0, blank=True, null=True ) location = models.CharField( _("In store location"), max_length=50, blank=True, null=True ) # Date information date_created = models.DateTimeField( _("Date Created"), auto_now_add=True ) date_updated = models.DateTimeField( _("Date Updated"), auto_now=True, db_index=True ) class Meta: verbose_name = _("Store Stock Record") verbose_name_plural = _("Store Stock Records") objects = GeoManager() # Needed for distance queries against stores def __unicode__(self): if self.store and self.product: return "%s @ %s" % (self.product.title, self.store.name) return "Store Stock" @property def is_available_to_buy(self): return self.num_in_stock > self.num_allocated
class GeometryModel(models.Model): name = models.CharField(max_length=255) geometry = GeometryField(srid=settings.SRID) objects = GeoManager() def __str__(self): return self.name
class Place(models.Model): name = models.CharField(max_length=200) listening_to = models.CharField(max_length=10, blank=True) public = models.CharField(max_length=3, blank=True) objects = GeoManager() def __unicode__(self): return self.name
class Location(models.Model): name = models.CharField(max_length=255, null=False, blank=False) location = PointField(null=True, blank=False, geography=True) date = models.DateField(blank=True, null=True) date_time = models.DateTimeField(blank=True, null=True) objects = GeoManager() def __unicode__(self): return self.name
class Parada(models.Model): objects = GeoManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) token = models.ForeignKey(Token, related_name='paradas') nome = models.CharField(max_length=100, null=True, blank=True) avaliacao = models.IntegerField(default=0, null=False) local = PointField(null=False) comentario = models.TextField(null=True, blank=True) foto = models.TextField(null=True, blank=True)
class LastKnownPosition(models.Model): """ De-normalization to speed up last position lookups. """ unit_id = models.PositiveIntegerField(unique=True) timestamp = models.DateTimeField(db_index=True) location = LocationField() modified_on = models.DateTimeField(auto_now=True) objects = GeoManager()
def forwards(self, orm): GeoManager().contribute_to_class(orm.Trip, "objects") GeoManager().contribute_to_class(orm.Stop, "objects") GeoManager().contribute_to_class(orm.Shape, "objects") for trip in orm.Trip.objects.all(): if trip.shape_id: shape = orm.Shape.objects.get(id=trip.shape_id) trip.geometry = shape.geometry trip.save() else: stoptimes = trip.stoptime_set.order_by('stop_sequence') if stoptimes.count() > 1: points = [] for st in stoptimes.all(): stop = orm.Stop.objects.get(id=st.stop_id) points.append(stop.point.coords) ls = 'LINESTRING (' + ', '.join(['%s %s'%pt for pt in points]) + ')' trip.geometry = ls trip.save()
def get_query_set(self): qs = BaseGeoManager.get_query_set(self) try: # First, check the global connection dictionary, because this # connection might have already been created. conn = connections[self.connection_name] except KeyError: conn = DatabaseWrapper(self.database_settings) connections[self.connection_name] = conn qs.query.connection = conn return qs
class PermitArea(models.Model): '''Stores information about a single permit''' # The region field stores the geometric shape(s) of the permit region = models.MultiPolygonField(srid=4326, blank=False) # We need the category in order to color the map #category = models.CharField(max_length=1024, blank=False) category = models.CharField(max_length=7, choices=((SITE_SUBPLAN, SITE_SUBPLAN), (REZONE, REZONE)), blank=False) # What township contains this region? township = models.CharField(max_length=4, choices=((CARY, CARY), (APEX, APEX)), blank=False) # Keep track of when we've seen this field first_seen = models.DateField() last_seen = models.DateField() # This manager is what allows us to make GIS queries (such as # contains, overlap, bbcontains, etc.). It must be the main # manager on this model type or we cannot make these queries. objects = GeoManager() def get_timeline_data(self): result = dict([(field, []) for field in PermitData.VALUE_FIELDS]) result['info_link'] = [] for row in self.data.all().order_by('-saved_on'): for field in PermitData.VALUE_FIELDS: value = getattr(row, field) if value is not None: result[field].append({ 'value': value, 'date': row.saved_on.isoformat() }) if (row.info_link is not None): result['info_link'].append(row.info_link.to_dict()) return result def to_dict(self): centroid = self.region.centroid return { 'first_seen': self.first_seen.isoformat(), 'last_seen': self.last_seen.isoformat(), 'centroid': [centroid.y, centroid.x], 'data': self.get_timeline_data(), 'category': self.category, 'township': self.township, 'id': self.id }
class VKUser(Model): vk_id = CharField(max_length=100, primary_key=True, unique=True) vk_token = CharField(max_length=400) phone = CharField(max_length=50, blank=True) is_phone_confirmed = BooleanField(default=False) email = TextField(blank=True) is_email_confirmed = BooleanField(default=False) auth_token = UUIDField(default=uuid4, editable=True) create_datetime = DateTimeField(auto_now_add=True) city = CharField(max_length=400, null=True, blank=True, default=None) point = PointField(null=True, blank=True, default=None) objects = GeoManager() def __str__(self): return str(self.vk_id)
class PermitData(models.Model): # Attach this PermitData object to a specific PermitArea object owner = models.ForeignKey(PermitArea, related_name='data') # These are basic fields supported by all the municipalities that we # currently pull data from. They are all character fields. name = models.CharField(max_length=1024, null=True) proj_id = models.CharField(max_length=1024, null=True) #link = models.CharField(max_length=1024, null=True) info_link = models.ForeignKey(InfoLink, null=True) status = models.CharField(max_length=1024, null=True) comment = models.TextField(null=True) # We also store this here in case it changes over time. # Having it here also gives us full text search on category category = models.CharField(max_length=1024, null=True) # Date on which the values in this row were captured saved_on = models.DateField() # We must use a GeoManager because of our foreign key relation to the # PermitArea object. Otherwise we'll get errors. objects = GeoManager() VALUE_FIELDS = ('name', 'comment', 'proj_id', 'status', 'category') # In order to support full text search, we have a SECOND model # that allows for that access pattern. Attempts to use the GIS # mixin that is available in the pgfulltext module failed # miserably, so we go with this route for now. The main drawback # is that we must manually update the search fields on save # because this is not the default manager. That's not too terrible, # however, because we only ever save from one place inside kmlutils.py. search_index = VectorField() text = SearchManager( # List all the fields that you want indexed fields=VALUE_FIELDS, # This may be redundant now. Not sure. auto_update_search_field=False) @classmethod def create_query_dict(cls, area, data_dict): for field in PermitData.VALUE_FIELDS: if field not in data_dict: data_dict[field] = None data_dict['owner'] = area return data_dict
class Facility(models.Model): category = models.ForeignKey(FacilityCategory) name = models.CharField(max_length=255, help_text='If the facility has a specific name', blank=True, null=True) description = models.TextField(blank=True) location = models.PointField(unique=True) # Important - it deals with the location stuff objects = GeoManager() def __unicode__(self): string = "Facility %d, %s" % (self.pk, self.category) if self.name: string += ": %s" % self.name return string class Meta: app_label = 'facilities' verbose_name_plural = 'facilities'
class Flatshare(models.Model): token = models.CharField(max_length=20, default=generate_flatshare_token) admin = models.ForeignKey(User) name = models.CharField(max_length=50, blank=True, null=True) size = models.PositiveIntegerField() max_guests = models.PositiveIntegerField(validators=[MinValueValidator(2)]) address = models.CharField(max_length=200) location = PointField() latest_pairing = models.ForeignKey('pairings.Pairing', blank=True, null=True, on_delete=models.SET_NULL) objects = GeoManager() def __unicode__(self): return unicode(self.id)
class Route(models.Model): title = models.TextField() external_id = models.IntegerField() route_type = models.CharField(max_length=100, choices=TYPES) route_loop = models.BooleanField() technical_difficulty = models.IntegerField(choices=DIFFICULTIES) route_length = models.FloatField() route_uphill = models.FloatField() route_downhill = models.FloatField() route_height = models.FloatField() route_low = models.FloatField() time = models.CharField(max_length=100, null=True, blank=True) coordinates = models.CharField(max_length=100, null=True, blank=True) upload_date = models.CharField(max_length=100, null=True, blank=True) recorded_date = models.CharField(max_length=100, null=True, blank=True) stars = models.IntegerField(null=True) start_point = PointField() line = LineStringField() objects = GeoManager()
class Spot(models.Model): DANGER_LEVEL_CHOICES = [(i,i) for i in range(1, 11)] SKILL_LEVEL_CHOICES = [(i,i) for i in range(1, 11)] user = models.ForeignKey(User, related_name="spots") primary_photo = models.FileField(upload_to="primary-photos/") title = models.CharField(max_length=250) description = models.CharField(max_length=1000, null=True) skill_level = models.SmallIntegerField(choices=SKILL_LEVEL_CHOICES, null=True) danger_level = models.SmallIntegerField(choices=DANGER_LEVEL_CHOICES, null=True) family_safe = models.NullBooleanField(null=True) location = LineStringField() feature_types = models.ManyToManyField(FeatureType, related_name="spots", null=True) activity_types = models.ManyToManyField(ActivityType, related_name="spots", null=True) created_at = models.DateTimeField(default=timezone.now) objects = GeoManager() def __unicode__(self): return self.title
class CallForTenders(models.Model): title = models.CharField(_(u'title'), max_length=200) activity = models.ManyToManyField('coop_local.ActivityNomenclature', verbose_name=_(u'activity sector')) organization = models.ForeignKey('Organization', verbose_name=_('organization')) areas = models.ManyToManyField('coop_local.Area', verbose_name=_(u'execution locations'), blank=True, null=True) allotment = models.BooleanField(_(u'allotment')) lot_numbers = models.CharField(_(u'lot numbers'), max_length=200, blank=True, help_text=u'Séparés par une virgule') deadline = models.DateTimeField(_(u'deadline')) clauses = MultiSelectField(_(u'clauses (si marché public)'), max_length=200, choices=CLAUSE_CHOICES, blank=True) url = models.URLField(u'URL', blank=True, null=True, max_length=250) en_direct = models.BooleanField(u'en direct', default=False) description = models.TextField(u'description synthétique', blank=True) objects = models.Manager() geo_objects = GeoManager() def __unicode__(self): return self.title def get_absolute_url(self): return '/appels-doffres/p/%u/' % self.id def activities(self): return ", ".join(self.activity.values_list('label', flat=True)) class Meta: verbose_name = _(u'Call for tenders') verbose_name_plural = _(u'Calls for tenders') app_label = 'coop_local'
class GeoLocation(models.Model): """ La localisation géographique d'une ressource """ # Entry associated address address = models.CharField(max_length=200, verbose_name=__('Adresse'), help_text=__("L'adresse postale du lieu")) # Entry associated location location = PointField(editable=False, verbose_name=__(u'Coordonnées'), help_text=__(u"Les coordonnées GPS du lieu")) # manager objects = GeoManager() def save(self, *args, **kwargs): g = geocoders.Nominatim() # this should be changed to openstreetmap try: place, (lat, lng) = g.geocode(self.address) self.location = fromstr("POINT(%s %s)" % (lng, lat)) self.address = place except geopy.exc.GeocoderServiceError: self.location = fromstr("POINT(0 0)") print "WARNING: could not geocode %s !!" % self.address super(GeoLocation, self).save(*args, **kwargs) @staticmethod def make_from_slug(slug): g = geocoders.Nominatim() # this should be changed to openstreetmap m = re_latitude_longitude.match(slug) lat = m.group(1) lng = m.group(2) location = fromstr("POINT(%s %s)" % (lng, lat)) address = g.reverse("%s, %s" % (lat, lng), exactly_one=1) return GeoLocation(address=address, location=location) @property def slug(self): return "%s, %s" % (self.location.get_x(), self.location.get_y()) def __unicode__(self): return self.address
class ProposedNews(Model): id = AutoField(primary_key=True) author = ForeignKey(VKUser, on_delete=CASCADE, null=True, blank=True, default=None) description = TextField() source_post = CharField(max_length=200, blank=True, default=None, null=True) vk_id_reference = CharField(max_length=200, blank=True, default=None, null=True) validate_status = CharField(max_length=200, choices=ValidateStatus, default=ValidateStatus[0][1]) validate_message = TextField(blank=True) cash = FloatField(default=0, blank=True) create_datetime = DateTimeField(auto_now_add=True) city = CharField(max_length=400, null=True, blank=True, default=None) point = PointField(null=True, blank=True, default=None) objects = GeoManager() def vk_url(self): if self.vk_id_reference: return "https://vk.com/wall{}_{}".format(LENTACH_ID, self.vk_id_reference) return None def photo(self): news_photos = NewsPhoto.objects.filter(proposed_news=self) return "{}{}".format(CURRENT_DOMAIN, news_photos[0].photo.url) if news_photos else None def __str__(self): return str(self.id)
class MapEntity(Model): # entityName = CharField(max_length=60, help_text="Insert name here") entityType = CharField(max_length=60, help_text="Insert name here") # entityType = ForeignKey(EventType, help_text="What type of event is it?") # entityDescription = TextField(max_length=300, help_text="Very awesome party at my place") owner = ForeignKey(User, on_delete=CASCADE) publishDate = DateTimeField(null=False, auto_now_add=True) # lastModDate = DateTimeField(null=True, auto_now=True) # uuid = UUIDField(default=uuid.uuid4, editable=False) geoLocationField = PointField(srid=4326) objects = GeoManager() def setLocationField(self, lat, lng): self.geoLocationField = GEOSGeometry('POINT(' + str(lng) + ' ' + str(lat) + ')', srid=4326) # json encode maybe?! def __str__(self): return str(self.entityType + ":::" + str(self.geoLocationField))
class UserProfile(UserenaBaseProfile): user = models.OneToOneField(User, unique=True, verbose_name=_('user'), related_name="userprofile") phone = models.IntegerField(_('phone'), null=True, blank=True) celular = models.IntegerField(_('mobile'), null=True, blank=True) state = models.CharField(_('state'), max_length=30, blank=True) city = models.CharField(_('city'), max_length=30, blank=True) image = StdImageField(_('image'), upload_to='statics/image_profile/', blank=True, variations={ 'large': (470, 470), 'thumbnail': (80, 80, True), 'small': (180, 180, True) }) zipcode = models.IntegerField(_('zipcode'), null=True, blank=True) adress = models.CharField(_('address'), max_length=50, blank=True) terms = models.BooleanField(_('terms'), default=False) welcome = models.BooleanField(default=False) categories = models.ManyToManyField(Category) coords = PointField(null=True) objects = GeoManager()
class PostalCode(Place, SlugModel): slug_contains_id = True code = models.CharField(max_length=20) location = PointField() country = models.ForeignKey(swapper.get_model_name('cities', 'Country'), related_name='postal_codes', on_delete=SET_NULL_OR_CASCADE) # Region names for each admin level, region may not exist in DB region_name = models.CharField(max_length=100, db_index=True) subregion_name = models.CharField(max_length=100, db_index=True) district_name = models.CharField(max_length=100, db_index=True) region = models.ForeignKey(Region, blank=True, null=True, related_name='postal_codes', on_delete=SET_NULL_OR_CASCADE) subregion = models.ForeignKey(Subregion, blank=True, null=True, related_name='postal_codes', on_delete=SET_NULL_OR_CASCADE) city = models.ForeignKey(swapper.get_model_name('cities', 'City'), blank=True, null=True, related_name='postal_codes', on_delete=SET_NULL_OR_CASCADE) district = models.ForeignKey(District, blank=True, null=True, related_name='postal_codes', on_delete=SET_NULL_OR_CASCADE) objects = GeoManager() class Meta: unique_together = ( ('country', 'region', 'subregion', 'city', 'district', 'name', 'id', 'code'), ('country', 'region_name', 'subregion_name', 'district_name', 'name', 'id', 'code'), ) @property def parent(self): return self.country @property def name_full(self): """Get full name including hierarchy""" return force_text(', '.join(reversed(self.names))) @property def names(self): """Get a hierarchy of non-null names, root first""" return [e for e in [ force_text(self.country), force_text(self.region_name), force_text(self.subregion_name), force_text(self.district_name), force_text(self.name), ] if e] def __str__(self): return force_text(self.code) def slugify(self): if self.id: return '{}-{}'.format(self.id, unicode_func(self.code)) return None
class Organization(models.Model): name = models.CharField("Organization Name", max_length=255) type = models.ForeignKey(OrganizationType, verbose_name='Type of Organization') phone = models.CharField("Contact Number", max_length=255, blank=True, null=True) fax = models.CharField(max_length=255, blank=True, null=True) email = models.EmailField(blank=True, null=True) website = models.URLField(blank=True, null=True) country = models.CharField(max_length=3, choices=COUNTRIES, default=u'NPL') address = models.TextField(blank=True, null=True) public_desc = models.TextField("Public Description", blank=True, null=True) additional_desc = models.TextField("Additional Description", blank=True, null=True) logo = models.ImageField(upload_to="logo", default="logo/default_org_image.jpg") is_active = models.BooleanField(default=True) location = PointField( geography=True, srid=4326, blank=True, null=True, ) date_created = models.DateTimeField(auto_now_add=True, blank=True) logs = GenericRelation('eventlog.FieldSightLog') class Meta: ordering = [ '-is_active', 'name', ] def __unicode__(self): return u'{}'.format(self.name) objects = GeoManager() @property def latitude(self): if self.location: return self.location.y @property def longitude(self): if self.location: return self.location.x def getname(self): return self.name @property def status(self): if self.organization_instances.filter(form_status=1).count(): return 1 elif self.organization_instances.filter(form_status=2).count(): return 2 elif self.organization_instances.filter(form_status=0).count(): return 0 elif self.organization_instances.filter(form_status=3).count(): return 3 return 4 def get_organization_submission(self): instances = self.organization_instances.all().order_by('-date') outstanding, flagged, approved, rejected = [], [], [], [] for submission in instances: if submission.form_status == 0: outstanding.append(submission) elif submission.form_status == 1: rejected.append(submission) elif submission.form_status == 2: flagged.append(submission) elif submission.form_status == 3: approved.append(submission) return outstanding, flagged, approved, rejected def get_submissions_count(self): from onadata.apps.fsforms.models import FInstance outstanding = FInstance.objects.filter(project__organization=self, project__is_active=True, form_status=0).count() rejected = FInstance.objects.filter(project__organization=self, project__is_active=True, form_status=1).count() flagged = FInstance.objects.filter(project__organization=self, project__is_active=True, form_status=2).count() approved = FInstance.objects.filter(project__organization=self, project__is_active=True, form_status=3).count() return outstanding, flagged, approved, rejected def get_absolute_url(self): return reverse('fieldsight:organizations-dashboard', kwargs={'pk': self.pk}) @property def get_staffs(self): staffs = self.organization_roles.filter( group__name="Organization Admin").values_list( 'id', 'user__username') return staffs @property def get_staffs_org(self): staffs = self.organization_roles.filter( group__name="Organization Admin") return staffs @property def get_staffs_id(self): return self.organization_roles.filter( group__name="Organization Admin").values_list('id', flat=True) def get_organization_type(self): return self.type.name
def __init__(self, connection_name, *args, **kwargs): BaseGeoManager.__init__(self, *args, **kwargs) self.connection_name = connection_name self.database_settings = settings.DATABASES[connection_name]
def get_query_set(self): return GeoManager.get_query_set(self).select_related("geom")