我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用django.db.models.functions.Lower()。
def get_queryset(self): event = Event.objects.get(slug=self.kwargs.get('slug')) queryset = Ticket.objects.filter(type__event=event).order_by(Lower('last_name'), Lower('first_name')) search = self.request.GET.get('search') if search: queryset = queryset.filter( Q(first_name__icontains=search) | Q(last_name__icontains=search) | Q(email__icontains=search) ) registered_only = self.request.GET.get('registered_only') if registered_only: queryset = queryset.filter(status=Ticket.REGISTERED) return queryset
def sort_queryset(self, qs): sort_key = self.request.GET.get('sort') if sort_key: plain_key = sort_key[1:] if sort_key.startswith('-') else sort_key reverse = not (plain_key == sort_key) if plain_key in self.sortable_fields: is_text = False with suppress(FieldDoesNotExist): is_text = isinstance(qs.model._meta.get_field(plain_key), CharField) if is_text: # TODO: this only sorts direct lookups case insensitively # A sorting field like 'speaker__name' will not be found qs = qs.annotate(key=Lower(plain_key)).order_by('-key' if reverse else 'key') else: qs = qs.order_by(sort_key) return qs
def react_user_list(users, project, identifier): users = users.order_by(Lower('username')) user_list = ListSerializer(users, child=UserWithMailSerializer()).data format_strings = { 'users': json.dumps(user_list), 'project': project.pk, 'listen_to': identifier, } return format_html( ( '<span data-euth-widget="userlist"' ' data-users="{users}"' ' data-project="{project}"' ' data-listen-to="{listen_to}"></span>' ), **format_strings )
def to_representation(self, instance): data = super().to_representation(instance) moderators = UserWithMailSerializer( instance=instance.moderators.order_by(Lower('username')).all(), many=True, allow_empty=True, ) participants = UserWithMailSerializer( instance=instance.participants.order_by(Lower('username')).all(), many=True, allow_empty=True, ) data['moderators'] = moderators.data data['participants'] = participants.data return data
def lexical_ordering(self): """ Returns a case-insensitive lexical ordering of the tags. """ return self.order_by(Lower('text')) ########################################################################## ## Tag Manager ##########################################################################
def test_order_by_lower(self): from django.db.models.functions import Lower c = Category.objects.create(name='test') Blog.objects.create(title='A', title_nl='c', category=c) Blog.objects.create(title='a', title_nl='b', category=c) filtered = Blog.objects.filter(category=c) # order by title should result in aA because it is case sensitive. qs = filtered.order_by('title', 'title_nl') self.assertEquals(key(qs, 'title'), ['a', 'A']) # order by Lower('title') should result in Aa because lower('A') == lower('A') # so the title_nl field should determine the sorting qs = filtered.order_by(Lower('title'), 'title_nl') self.assertEquals(key(qs, 'title'), ['a', 'A']) # applying lower to title_nl should not matter since it is not the same letter qs = filtered.order_by(Lower('title_nl')) self.assertEquals(key(qs, 'title'), ['a', 'A']) # should be the same as previous with override('nl'): qs = filtered.order_by(Lower('title_i18n')) self.assertEquals(key(qs, 'title'), ['a', 'A'])
def test_values_kwarg_lower(self): from django.db.models.functions import Lower qs1 = Blog.objects.values(lower_name=Lower('category__name')) qs2 = Blog.objects.values(lower_name=Lower('category__name_en')) self.assertEquals(list(qs1), list(qs2))
def campaign_list(request): '''Renders a template showing a list of registered campaigns, sorted in alphabetical order. Campaigns are created by the user, who provides a hashtag and time range in which to search.''' campaigns = Campaign.objects.order_by(Lower('Campaign_Title').asc()) return render(request, 'ig_miner_app/campaign_list.html', {'campaigns': campaigns})
def print_categories(categories, server_type, maps_set): for c in categories: maps = Map.objects.filter(server_type=server_type, categories=c).order_by(Lower('name')) # TODO: at some point this should not be neccessary anymore if maps and not maps_set.issuperset(maps): print() print('??? ' + c.name.upper() + ' ???') for m in maps: if m not in maps_set: maps_set.add(m) print_map(m)
def print_mapfile(server_type): print('$add_vote "Make sure no one is racing before voting!" "info"') print('$add_vote "Random {} Map" "random_map"'.format(server_type)) print('$add_vote "Random {} Map Unfinished by Vote Caller" "random_unfinished_map"'.format(server_type)) if server_type != 'DDmaX': print() print('??? NEW MAPS ???') maps = Map.objects.filter(server_type=server_type).order_by('-timestamp')[:7] maps_set = set(maps) for m in maps: print_map(m) else: maps_set = set() categories = MapCategory.objects.filter(order__lte=100).order_by('order', 'name') print_categories(categories, server_type, maps_set) print() print('??? OTHER MAPS ???') for m in Map.objects.filter(server_type=server_type, categories=None).order_by(Lower('name')): if m not in maps_set: print_map(m) categories = MapCategory.objects.filter(order__gt=100).order_by('order', 'name') print_categories(categories, server_type, maps_set)
def list(self, request, *args, **kwargs): '''List the available tilesets Args: request (django.http.HTTPRequest): The HTTP request containing no parameters Returns: django.http.JsonResponse: A json file containing a 'count' as well as 'results' with each tileset as an entry ''' # only return tilesets which are accessible by this user if request.user.is_anonymous: user = gu.get_anonymous_user() else: user = request.user queryset = self.queryset.filter( dbm.Q(owner=user) | dbm.Q(private=False) ) if 'ac' in request.GET: # Autocomplete fields queryset = queryset.filter(name__contains=request.GET['ac']) if 't' in request.GET: # Filter by filetype queryset = queryset.filter(filetype=request.GET['t']) if 'dt' in request.GET: # Filter by datatype queryset = queryset.filter(datatype__in=request.GET.getlist('dt')) if 'o' in request.GET: if 'r' in request.GET: queryset = queryset.order_by(dbmf.Lower(request.GET['o']).desc()) else: queryset = queryset.order_by(dbmf.Lower(request.GET['o']).asc()) #ts_serializer = tss.UserFacingTilesetSerializer(queryset, many=True) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = ts_serializer(queryset, many=True) return JsonResponse(serializer.data) """ return JsonResponse( {"count": len(queryset), "results": ts_serializer.data} ) """
def dashboard(request): newsletter, _ = Newsletter.objects.get_or_create(user=request.user, defaults={ "email": request.user.email, }) # Set forms on existing sources sources = newsletter.source_set.all().order_by(Lower('name')) for source in sources: # Handle updates is_updating = False try: is_updating = (int(request.GET.get("update", None)) == source.id) except (ValueError, TypeError): pass # Only bind the form to POST if its the one being updated source.form = SourceForm(request.POST if is_updating else None, instance=source, prefix="source-%s" % source.id) if request.POST and is_updating and source.form.is_valid(): # Handle deletes if source.form.cleaned_data["delete"]: source.delete() return form_complete(request, "Removed %s!" % source.name) source.form.save() source.refresh_from_db() return form_complete(request, "Updated %s!" % source.name) # Set up new source form is_adding = "add" in request.GET add_form = SourceForm(request.POST if is_adding else None, prefix="new-source", initial={"newsletter": newsletter}) if add_form.is_valid(): obj = add_form.save(commit=False) obj.newsletter = newsletter obj.save() return form_complete(request, "Added %s!" % obj.name) return render(request, "dashboard.html", { "newsletter": newsletter, "add_form": add_form, "sources": sources, })