class BaseTransaction(models.Model): origin = models.ForeignKey('coop_local.Exchange',related_name='origin') destination = models.ForeignKey('coop_local.Exchange',related_name='destination') title = models.CharField(_('Titre'),blank=True,max_length=250) description = models.TextField(_(u'Description'),blank=True) created = exfields.CreationDateTimeField(_(u'Création'),null=True) modified = exfields.ModificationDateTimeField(_(u'Modification'),null=True) uuid = exfields.UUIDField() #nécessaire pour URI de l'engagement class Meta: abstract = True
class Pais(models.Model): nombre = models.CharField(max_length=150) slug = AutoSlugField(populate_from='nombre', max_length=255) uuid = ext_fields.UUIDField(auto=True) area = models.PolygonField(null=True, blank=True) objects = models.GeoManager() def __unicode__(self): return self.nombre class Meta: verbose_name_plural = "Paises"
class Barrio(models.Model): nombre = models.CharField(max_length=150) slug = AutoSlugField(populate_from='nombre', max_length=255) ciudad = models.ForeignKey(Ciudad, on_delete=models.CASCADE) uuid = ext_fields.UUIDField(auto=True) area = models.PolygonField(null=True, blank=True) objects = models.GeoManager() def __unicode__(self): return self.nombre class Meta: verbose_name_plural = "Barrios"
class BeerDBModel(models.Model): class Meta: abstract = True id = ext_fields.UUIDField(auto=True, primary_key=True) revision = models.IntegerField(default=0, editable=False) added = models.DateTimeField(default=datetime.datetime.now, editable=False) edited = models.DateTimeField(editable=False) def save(self, *args, **kwargs): self.revision += 1 self.edited = datetime.datetime.now() super(BeerDBModel, self).save(*args, **kwargs)
class Region(models.Model): name = models.CharField(max_length=255) slug = AutoSlugField(populate_from='name', max_length=255) uuid = ext_fields.UUIDField(auto=True) creator = models.ForeignKey('auth.User', related_name='regions', default='1') # Geo Django field to store a polygon area = models.PolygonField() price = models.IntegerField() # You MUST use GeoManager to make Geo Queries objects = models.GeoManager()
class BaseEngagement(models.Model): membre = models.ForeignKey('coop_local.Membre') initiative = models.ForeignKey('coop_local.Initiative') role = models.ForeignKey('coop_local.Role') created = exfields.CreationDateTimeField(_(u'Création'), null=True) modified = exfields.ModificationDateTimeField(_(u'Modification'), null=True) #membre_uri = models.CharField(_(u'Profil FOAF'),blank=True, max_length=250, editable=False) uuid = exfields.UUIDField() #nécessaire pour URI de l'engagement class Meta: abstract = True '''
class Inmueble(models.Model): creador = models.ForeignKey('auth.User') titulo = models.CharField(max_length=60, blank=False) descripcion = models.CharField(max_length=20, null=True, blank=True) banos = models.CharField(max_length=5, null=True, blank=True) habitaciones = models.CharField(max_length=5, null=True, blank=True) metros_terreno = models.CharField(max_length=5, null=True, blank=True) metros_cubiertos = models.CharField(max_length=5, null=True, blank=True) email = models.EmailField(null=True, blank=False) info = models.TextField(null=True, blank=True) fecha_creacion = models.DateTimeField(auto_now_add=True) fecha_publicacion = models.DateTimeField(blank=True, null=True) direccion = models.CharField(max_length=150, blank=False) location = models.PointField(u"longitude/latitude", geography=True, blank=True, null=True) gis = models.GeoManager() objects = models.Manager() pais = models.ForeignKey(Pais, on_delete=models.CASCADE) ciudad = models.ForeignKey(Ciudad, on_delete=models.CASCADE) barrio = models.ForeignKey(Barrio, on_delete=models.CASCADE) slug = AutoSlugField(populate_from='titulo', max_length=255) uuid = ext_fields.UUIDField(auto=True) def publish(self): self.fecha_publicacion = timezone.now() self.save() def __str__(self): return self.titulo def save(self, **kwargs): if not self.location: address = u'%s %s' % (self.ciudad.nombre, self.direccion) address = address.encode('utf-8') geocoder = GoogleV3() try: _, latlon = geocoder.geocode(address) except (URLError, GeocoderQueryError, ValueError): pass else: point = "POINT(%s %s)" % (latlon[1], latlon[0]) self.location = geos.fromstr(point) super(Inmueble, self).save() class Meta: verbose_name_plural = "Inmuebles"
class BaseSite(models.Model): title = models.CharField(_('Titre'), null=True, blank=True, max_length=250) description = models.TextField(_(u'Description'), null=True, blank=True) site_principal = models.BooleanField(default=True) uri = models.CharField(_(u'URI principale'), null=True, blank=True, max_length=250, editable=False) location = models.ForeignKey(Location, related_name='sites') initiative = models.ForeignKey('coop_local.Initiative', null=True, blank=True, related_name='sites') adr1 = models.CharField(null=True, blank=True, max_length=100) adr2 = models.CharField(null=True, blank=True, max_length=100) zipcode = models.CharField(null=True, blank=True, max_length=5) city = models.CharField(null=True, blank=True, max_length=100) latlong = models.CharField(null=True, blank=True, max_length=100) lat = models.CharField(null=True, blank=True, max_length=100) long = models.CharField(null=True, blank=True, max_length=100) created = exfields.CreationDateTimeField(_(u'Création'), null=True) modified = exfields.ModificationDateTimeField(_(u'Modification'), null=True) #membre_uri = models.CharField(_(u'Profil FOAF'),blank=True, max_length=250, editable=False) uuid = exfields.UUIDField(null=True) #nécessaire pour URI de l'engagement class Meta: abstract = True def __unicode__(self): if self.title != None: return self.title + u', ' + self.city else: return self.adr1 + u', ' + self.city def get_absolute_url(self): return reverse('place_detail', args=[self.uuid]) def links(self): links = { 'inits': self.initiative_set.all().count() - 1, 'events': self.event_set.all().count() - 1 } return links
class GeoPoly(geomodels.Model): name = models.CharField(max_length=200, null=True, blank=True) location = models.OneToOneField(Location, null=True, related_name='poly') uuid = ext_fields.UUIDField(version=4, null=True) global_id_text = models.CharField(max_length=200, null=True, blank=True) code = models.CharField(max_length=100, null=True, blank=True) parent_code = models.CharField(max_length=100, null=True, blank=True) source = models.CharField(max_length=100, null=True, blank=True) created_at = ext_fields.CreationDateTimeField() last_modified = ext_fields.ModificationDateTimeField() last_modified_gis = models.DateField(null=True) geom = geomodels.MultiPolygonField(srid=4326) objects = geomodels.GeoManager() class Meta: verbose_name = "Geo Location Polygon"
class Location(MPTTModel): parent = TreeForeignKey('self', null=True, related_name='children') uuid = ext_fields.UUIDField(version=4, primary_key=True) name = models.CharField(max_length=100, default="Unknown") alt_names = models.CharField(max_length=200, null=True, blank=True) location_type = models.ForeignKey(LocationType) created_at = ext_fields.CreationDateTimeField() last_modified = ext_fields.ModificationDateTimeField() @property def gis(self): try: return self.poly except GeoPoly.DoesNotExist: try: return self.point except GeoPoint.DoesNotExist: return None def __str__(self): return "%s" % self.name class Meta: verbose_name = "Location"
class Location(MPTTModel): """Core Location model HP - Health Post (POSTO DE SAÚDE POS) OTHER - Other Clinic/TB treatment center (DISPENSÁRIO ANTI TUBERCULOSE OUTRO) CH - Central Hospital - Pediatric, Mental, Provincial Hospital (HOSPITAL CENTRAL HP) HOS - Hospital MH - Mental Hospital (Special Hospital HN/HC) MC - Maternity Center (CENTRO MATERNO INFANTIL CMI) HC - Health Center (CENTRO DE SAÚDE CEN) WH - Warehouse """ FACTYPES = ( ('HP', _('Health Post')), ('MH', _('Mental Hospital')), ('MC', _('Maternity Center')), ('HC', _('Health Center')), ('CH', _('Central Hospital')), ('HOS', _('Hospital')), ('WH', _('Warehouse')), ('OTHER', _('Other')), ) parent = TreeForeignKey('self', null=True, blank=True, related_name='children') name = models.CharField(max_length=100, default=_('Unknown Name')) alt_names = models.CharField( max_length=150, blank=True, null=True, help_text=_('List of Alternate Place Names separated by (|)')) hcid = models.CharField(max_length=16, db_index=True, null=True, unique=True, blank=True, help_text='Unique ID: AABBCC##') srcid = models.CharField( max_length=75, db_index=True, blank=True, null=True, help_text=_('Code provided from source agency. HASC for GADM shapes.')) loc_type = models.ForeignKey(LocationType) fac_type = models.CharField(max_length=5, choices=FACTYPES, null=True, blank=True) slug = ext_fields.AutoSlugField(populate_from='hcid', unique=True, max_length=16) uuid = ext_fields.UUIDField() created_at = ext_fields.CreationDateTimeField() updated_at = ext_fields.ModificationDateTimeField() class MPTTMeta: order_insertion_by = ['hcid'] @classmethod def root(cls): obj = None root_loc_type = LocationType.root() try: obj = cls.objects.get(loc_type=root_loc_type) except cls.DoesNotExist: pass return obj @classmethod def get_by_code(cls, code): obj = None try: obj = cls.objects.get(hcid__iexact=code) except cls.DoesNotExist: return obj return obj @classmethod def get_sites(cls, queryset=None): if queryset is None: queryset = cls.objects.all() site_type = LocationType.get_site_type() if site_type is None: _logger.warning('No code for the site location type defined.') return [] else: return queryset.filter(loc_type=site_type) def get_site_descendants(self): sites = Location.get_sites(self.get_descendants(True)) return sites def active_site_count(self, program, year): sites = self.get_site_descendants() if year is None or year == date.today().year: return LocationProgramState.objects.filter( program=program, site__in=sites, current_state__startswith='ACTIVE').count() else: return ProgramReport.objects.filter( program=program, report_date__year=year, site__in=sites).order_by('site').distinct('site').count() def inactive_site_count(self, program, year): sites = self.get_site_descendants() if year is None or year == date.today().year: return LocationProgramState.objects.filter( program=program, site__in=sites, current_state__startswith='INACTIVE').count() else: return self.reporting_site_count( program, year) - self.active_site_count(program, year) def reporting_site_count(self, program, year): sites = self.get_site_descendants() if year is None or year == 0 or year == date.today().year: return LocationProgramState.objects.filter( program=program, site__in=sites).exclude(current_state='OUT').count() else: return ProgramReport.objects.filter( program=program, report_date__lte='{:04d}-12-31'.format(year), site__in=sites).order_by('site').distinct('site').count() @classmethod def get_location_choices(cls, type_code_exclude_list=None): qs = cls.objects.select_related('loc_type') if type_code_exclude_list: qs = qs.exclude(loc_type__code__in=type_code_exclude_list) displayed_locations = qs.values('pk', 'name', 'loc_type__name') filter_locations = {} for loc_data in displayed_locations: filter_locations.setdefault(loc_data['loc_type__name'], []).append( (loc_data['pk'], loc_data['name'])) return [['', '']] + [[loc_type, filter_locations[loc_type]] for loc_type in filter_locations.keys()] def __str__(self): return smart_text(self.name) def __unicode__(self): return self.__str__ @property def location_breadcrumb(self): return ' > '.join( str(loc.name) for loc in self.get_ancestors(include_self=True)) def location_path(self, include_self=False): path = list( self.get_ancestors(include_self).values_list('name', flat=True)) path.reverse() return ', '.join(path[:-1]) @property def geom(self): try: return self.location_gadm.geom except Gadm.DoesNotExist: try: return self.location_pnt.geom except SiteLocation.DoesNotExist: return None @property def is_site(self): site_type = LocationType.get_site_type() return self.loc_type == site_type @property def printable_programmes(self): return ', '.join( self.site_programs.values_list('description', flat=True))