def words_restriction( queryset, words, broad, search_in_tags ): #{{{1 if not words: return queryset q_filters = None for word in words: if not word: continue # NOTE: city needs to be icontains to find e.g. 'washington' in # 'Washington D.C.' # TODO: search toponyms in other languages if queryset.model == Event: q_word_filters = \ Q(title__icontains = word) | \ Q(city__icontains = word) | \ Q(country__iexact = word) | \ Q(acronym__icontains = word) else: q_word_filters = \ Q(event__title__icontains = word) | \ Q(event__city__icontains = word) | \ Q(event__country__iexact = word) | \ Q(event__acronym__icontains = word) if search_in_tags: if queryset.model == Event: q_word_filters |= Q(tags__icontains = word) else: q_word_filters |= Q(event__tags__icontains = word) if broad: if queryset.model == Event: q_word_filters |= \ Q( address__icontains = word ) | \ Q( description__icontains = word ) | \ Q( urls__url_name__icontains = word ) | \ Q( urls__url__icontains = word ) | \ Q( dates__eventdate_name__icontains = word ) | \ Q( sessions__session_name__icontains = word ) else: q_word_filters |= \ Q( event__address__icontains = word ) | \ Q( event__description__icontains = word ) | \ Q( event__urls__url_name__icontains = word ) | \ Q( event__urls__url__icontains = word ) | \ Q( event__dates__eventdate_name__icontains = word ) | \ Q( event__sessions__session_name__icontains = word ) if not q_filters: q_filters = q_word_filters else: q_filters &= q_word_filters # FIXME: events with partial words are matches, WTF return queryset.filter( q_filters )
def q_object_for_eq(self): dc = {} dc[self.attribute_name] = self.convert_value_for(self.raw_value_as_str) return Q(**dc)
def exclusion( queryset, query ): #{{{1 """ returns a tuple (a queryset an a string ) restricting ``queryset`` excluding events if ``query`` contains expressions starting with ``-`` """ for word in EXCLUSION_REGEX.findall(query): if queryset.model == Event: if word[0] == '#': if len(word) == 1: # it is only '-#', we exclude all tagged events exclusion_q = Q(tags__isnull = False) else: exclusion_q = Q(tags__icontains = word[1:]) elif word[0] == '@': if len(word) == 1: # it is only '-@', we exclude all located events exclusion_q = \ Q(city__isnull = False) | \ Q(country__isnull = False) | \ Q(coordinates__isnull = False) | \ Q(address__isnull = False) else: exclusion_q = \ Q(city__icontains = word[1:]) | \ Q(country__icontains = word[1:]) else: exclusion_q = \ Q(title__icontains = word) | \ Q(city__icontains = word) | \ Q(country__iexact = word) | \ Q(acronym__icontains = word) | \ Q(tags__icontains = word) else: assert queryset.model == EventDate if word[0] == '#': if len(word) == 1: # it is only '-#', we exclude all tagged events exclusion_q = Q(event__tags__isnull = False) else: exclusion_q = Q(event__tags__icontains = word[1:]) elif word[0] == '@': if len(word) == 1: # it is only '-@', we exclude all located events exclusion_q = \ Q(event__city__isnull = False) | \ Q(event__country__isnull = False) | \ Q(event__coordinates__isnull = False) | \ Q(event__address__isnull = False) else: exclusion_q = \ Q(event__city__icontains = word[1:]) | \ Q(event__country__icontains = word[1:]) else: exclusion_q = \ Q(event__title__icontains = word) | \ Q(event__city__icontains = word) | \ Q(event__country__iexact = word) | \ Q(event__acronym__icontains = word) | \ Q(event__tags__icontains = word) queryset = queryset.exclude(exclusion_q) query = EXCLUSION_REGEX.sub("", query) return queryset, query
def location_restriction( queryset, query ): #{{{1 """ returns a tuple (a queryset an a string ) restricting ``queryset`` with the locations of ``query`` and removing them from ``query`` """ for loc in LOCATION_REGEX.findall(query): if loc[11]: # name or name,name # name given, which can have a city, a comma and a country city, country = CITY_COUNTRY_RE.findall( loc[11] )[0] if not country: if queryset.model == Event: queryset = queryset.filter( Q( city__iexact = city ) | Q( country__iexact = city ) ) # TODO: use also translations of locations and # alternative names else: queryset = queryset.filter( Q( event__city__iexact = city ) | Q( event__country__iexact = city ) ) else: result = search_name( city + ', ' + country ) if result: point = result.get('coordinates', None) else: point = None distance = { settings.DISTANCE_UNIT_DEFAULT: settings.CITY_RADIUS, } if queryset.model == Event: if point: # example: ...coordinates__distance_lte=(pnt, D(km=7))) queryset = queryset.filter( Q( city__iexact=city, country__iexact=country ) | Q( coordinates__distance_lte = ( point, D( **distance ) ) ) ) else: queryset = queryset.filter( city__iexact = city, country__iexact = country ) else: if point: queryset = queryset.filter( Q( event__city__iexact = city, event__country__iexact = country ) | Q( event__coordinates__distance_lte = ( point, D( **distance ) ) ) ) else: queryset = queryset.filter( event__city__iexact = city, event__country__iexact = country ) elif loc[8]: # name + distance + optional unit result = search_name( loc[8] ) if result: point = result.get('coordinates', None) else: point = None if not point: raise GeoLookupError() if loc[10]: distance = {loc[10]: loc[9],} else: distance = { settings.DISTANCE_UNIT_DEFAULT: loc[9],} # example: ...filter(coordinates__distance_lte=(pnt, D(km=7))) if queryset.model == Event: queryset = queryset.filter( coordinates__distance_lte = ( point, D( **distance ) ) ) else: queryset = queryset.filter( event__coordinates__distance_lte = ( point, D( **distance ) ) ) elif loc[4]: # coordinates given point = Point( float(loc[5]), float(loc[4]) ) if loc[7]: distance = {loc[7]: loc[6],} else: distance = { settings.DISTANCE_UNIT_DEFAULT: loc[6],} if queryset.model == Event: queryset = queryset.filter( coordinates__distance_lte = ( point, D( **distance ) ) ) else: queryset = queryset.filter( event__coordinates__distance_lte = ( point, D( **distance ) ) ) elif loc[0]: # We have 4 floats: longitude_west [0], longitude_east [1], # latitude_north [2], latitude_south [3] lng1 = float( loc[0] ) lat1 = float( loc[3] ) lng2 = float( loc[1] ) lat2 = float( loc[2] ) rectangle = Polygon( ((lng1, lat1), (lng2,lat1), (lng2,lat2), (lng1,lat2), (lng1, lat1)) ) if queryset.model == Event: queryset = queryset.filter( exact = True, coordinates__within = rectangle ) else: queryset = queryset.filter( event__exact = True, event__coordinates__within = rectangle ) else: pass # TODO: log error query = LOCATION_REGEX.sub("", query) return queryset, query
def test_q_object_for_in(self): q = self.fcq.q_object_for_in(str, 'sigla', ['ES,RJ']) self.assertEquals(Q(sigla__in=['ES,RJ']).__repr__(), q.__repr__())
def test_q_object_for_neq(self): q = self.fcq.q_object_for_neq(str, 'sigla', 'ES') self.assertEquals((~Q(sigla='ES')).__repr__(), q.__repr__())
def with_geometry(self, geom, distance=0, max_plots=1, species_preferenece=None, native=None, flowering=None, fall=None, edible=None, pests=None, dbhmin=None, dbhmax=None, species=None, sort_recent=None, sort_pending=None, has_tree=None, has_species=None, has_dbh=None): ''' Return a QuerySet with trees near a Point geometry or intersecting a Polygon geometry ''' plots = Plot.objects.filter(present=True) if geom.geom_type == 'Point': plots = plots.filter(geometry__dwithin=( geom, float(distance))).distance(geom).order_by('distance') else: plots = plots.filter(geometry__intersects=geom) if species_preferenece: plots_filtered_by_species_preference = plots.filter( tree__species__id=species_preferenece, tree__present=True) # If a species_preferenece is specified then any nearby trees with that species_preferenece will be # returned. If there are no trees for that species_preferenece, the nearest tree from any # species_preferenece will be returned. if len(plots_filtered_by_species_preference) > 0: plots = plots_filtered_by_species_preference if species: # Note that, unlike "preference", these values are forced plots = plots.filter(tree__species__pk=species, tree__present=True) if native is not None: if native: native = "True" else: native = "" plots = plots.filter(tree__species__native_status=native, tree__present=True) if flowering is not None: plots = plots.filter(tree__species__flower_conspicuous=flowering, tree__present=True) if fall is not None: plots = plots.filter(tree__species__fall_conspicuous=fall, tree__present=True) if edible is not None: plots = plots.filter(tree__species__palatable_human=edible, tree__present=True) if dbhmin is not None: plots = plots.filter(tree__dbh__gte=dbhmin, tree__present=True) if dbhmax is not None: plots = plots.filter(tree__dbh__lte=dbhmax, tree__present=True) if pests is not None: plots = plots.filter(tree__pests=pests) has_filter_q = None def filter_or(f, has): if has: return f | has else: return f if has_tree is not None: q_has_tree = Q(tree__present=True) if not has_tree: q_has_tree = ~q_has_tree has_filter_q = filter_or(q_has_tree, has_filter_q) if has_species is not None: if has_species: q_has_species = Q(tree__species__isnull=False, tree__present=True) else: # Note that Q(tree__present=False) seems to exlucde too # many records. Instead ~Q(tree__present=True) selects # all plots without tree records and those with trees # that are marked as not present q_has_species = Q( tree__species__isnull=True, tree__present=True) | (~Q(tree__present=True)) has_filter_q = filter_or(q_has_species, has_filter_q) if has_dbh is not None: q_has_dbh = Q(tree__dbh__isnull=(not has_dbh)) has_filter_q = filter_or(q_has_dbh, has_filter_q) if has_filter_q: plots = plots.filter(has_filter_q) if sort_recent: plots = plots.order_by('-last_updated') if sort_pending: plots_tree_pending = plots.filter( Q(tree__treepending__status='pending')) plots_plot_pending = plots.filter(Q(plotpending__status='pending')) if max_plots: plots = list(plots_tree_pending) + list(plots_plot_pending) # Uniquify plots_hash = {} for p in plots: plots_hash[p.pk] = p plots = plots_hash.values() plots = sorted(plots, key=lambda z: z.distance) plots = plots[:max_plots] extent = self.calc_extent(plots) else: if max_plots: plots = plots[:max_plots] if plots.count() > 0: extent = plots.extent() else: extent = [] return plots, extent
def q_object_for_spatial_operation(self): dc = {} value_conveted = self.convert_value_for(self.raw_value_as_str) dc[self.attribute_name + '__' + self.operation_or_operator] = value_conveted return Q(**dc)
def list(request): if request.method == 'POST': search = request.POST['search'] if search: match1 = Restaurant.objects.filter( Q(restaurant__startswith=search) | Q(rating__icontains=search) | Q(type__startswith=search) | Q(features__icontains=search)) if match1: return render(request, 'listing.html', {"match1": match1}) hospital = Hospital.objects.filter( Q(hospital_n__startswith=search) | Q(hospital_r__icontains=search) | Q(contact_nu__startswith=search) | Q(address__icontains=search)) if hospital: return render(request, 'listing.html', {"hospital": hospital}) market = Market.objects.filter( Q(market_nam__startswith=search) | Q(rating__icontains=search) | Q(location__startswith=search) | Q(longitude__icontains=search)) if market: return render(request, 'listing.html', {"market": market}) police = PoliceStation.objects.filter( Q(police_sta__icontains=search) | Q(rating__icontains=search) | Q(contact_nu__startswith=search) | Q(latitude__icontains=search)) if police: return render(request, 'listing.html', {"police": police}) match = Fort.objects.filter( Q(title__startswith=search) | Q(rating__icontains=search) | Q(category__startswith=search) | Q(descriptio__icontains=search)) if match: return render(request, 'listing.html', {"match": match}) else: return HttpResponse("No result Found") else: return HttpResponseRedirect('/') args = { "users": Fort.objects.all(), } return render(request, 'index.html', args)
def q_object_base_range(self, oper_operation): dc = {} arr_value = self.raw_value_as_str.split('&') arr_value_converted = [ self.convert_value_for(a_value) for a_value in arr_value] dc[self.attribute_name + '__' + oper_operation] = arr_value_converted return Q(**dc)
def resolve_snapshots(self, info): return Snapshot.objects.filter(Q_SNAPSHOT_ONLY_PUBLIC & Q(municipality__id=self.pk))
class GeoJSON(graphene.Scalar): @classmethod def serialize(cls, value): return json.loads(value.geojson) @convert_django_field.register(models.GeometryField) def convert_field_to_geojson(field, registry=None): return graphene.Field(GeoJSON, description=field.help_text, required=not field.null) Q_SNAPSHOT_ONLY_PUBLIC = Q(permission__exact=SnapshotPermission.PUBLIC) Q_SNAPSHOT_WITH_NOT_LISTED = Q(permission__lte=SnapshotPermission.NOT_LISTED) class SnapshotOnlyPublicFilter(FilterSet): class Meta: model = Snapshot fields = ['municipality__id', 'municipality__canton', 'is_showcase'] @property def qs(self): return super().qs.filter(Q_SNAPSHOT_ONLY_PUBLIC) class SnapshotNode(DjangoObjectType): class Meta:
def list(request): if request.method == 'POST': search = request.POST['search'] if search: restaurants = Restaurant.objects.filter( Q(restaurant__icontains=search) | Q(rating__icontains=search) | Q(type__startswith=search) | Q(features__icontains=search) ) marker_list = [] for instance in restaurants: name = str(instance.restaurant) latitude = float(instance.latitude) longitude = float(instance.longitude) marker_list += [[name, latitude, longitude]] if restaurants: context = { 'marker_list': json.dumps(marker_list), 'restaurents': restaurants, } return render(request, 'listing/restaurant.html', context) hospitals = Hospital.objects.filter( Q(hospital_n__icontains=search) | #Q(hospital_n__endswith=search) | Q(hospital_r__icontains=search) | Q(contact_nu__startswith=search) | Q(address__icontains=search) ) marker_list = [] for instance in hospitals: name = str(instance.hospital_n) latitude = float(instance.latitude) longitude = float(instance.longitude) marker_list += [[name, latitude, longitude]] if hospitals: context = { 'marker_list': json.dumps(marker_list), 'hospitals': hospitals, } return render(request, 'listing/hospital.html', context) markets = Market.objects.filter( Q(market_nam__icontains=search) | Q(rating__icontains=search) | Q(location__startswith=search) | Q(longitude__icontains=search) ) marker_list = [] for instance in markets: name = str(instance.market_nam) latitude = float(instance.latitude) longitude = float(instance.longitude) marker_list += [[name, latitude, longitude]] if markets: context = { 'marker_list': json.dumps(marker_list), 'markets': markets, } return render(request, 'listing/markets.html', context) polices = PoliceStation.objects.filter( Q(police_sta__icontains=search) | Q(rating__icontains=search) | Q(contact_nu__startswith=search) | Q(latitude__icontains=search) ) marker_list = [] for instance in polices: name = str(instance.police_sta) latitude = float(instance.latitude) longitude = float(instance.longitude) marker_list += [[name, latitude, longitude]] if polices: context = { 'marker_list': json.dumps(marker_list), 'polices': polices, } return render(request, 'listing/police.html', context) forts = Fort.objects.filter( Q(title__icontains=search) | Q(rating__icontains=search) | Q(category__startswith=search) | Q(descriptio__icontains=search) ) marker_list = [] for instance in forts: name = str(instance.title) latitude = float(instance.latitude) longitude = float(instance.longitude) marker_list += [[name, latitude, longitude]] if forts: context = { 'marker_list': json.dumps(marker_list), 'forts': forts, } return render(request, 'listing/fort.html', context) else: return render(request, 'success_or_not/searching_not_found.html') else: return HttpResponseRedirect('/') args = { "users": Fort.objects.all(), } return render(request, 'listing.html', args)