def descr_instances_reinit(request, descr_id=4): descr = ImplementationDescription.objects.get(pk=descr_id) cics = ComponentImplementationClass.objects.filter( technical_description_id=descr_id) cls = reinit_form_for_model(descr) InstanceFormSet = modelformset_factory(ComponentInstance, form=cls, extra=0) InstanceFormSet.form = staticmethod(curry(cls, cics=cics)) if request.POST: formset = InstanceFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() return redirect("ref:instance_descr_reinit", descr_id) else: instances = ComponentInstance.objects.filter(description_id=descr_id).\ prefetch_related(Prefetch('rel_target_set', queryset=ComponentInstanceRelation.objects.select_related('field'))).\ prefetch_related(Prefetch('field_set', queryset=ComponentInstanceField.objects.select_related('field'))).\ prefetch_related('environments') formset = InstanceFormSet(queryset=instances) return render_to_response("ref/instance_descr_reinit.html", { 'formset': formset, 'descr': descr })
def get_related(self, model): related_objects = [ 'statistical_unit', ] prefetch_objects = [ 'statuses', ] qs = model.objects.select_related(*related_objects).prefetch_related( *prefetch_objects) valid_statuses = get_status_queryset() dssdeinclusions = (models.DSSDEInclusion.objects.select_related( 'data_element', "data_element__valueDomain", "data_element__valueDomain__data_type").prefetch_related( Prefetch('data_element__statuses', valid_statuses, 'valid_statuses'))) dssclusterinclusions = (models.DSSClusterInclusion.objects. select_related('child').prefetch_related( Prefetch('child__statuses', valid_statuses, 'valid_statuses'))) qs = qs.prefetch_related( Prefetch('dssdeinclusion_set', dssdeinclusions)) qs = qs.prefetch_related( Prefetch('dssclusterinclusion_set', dssclusterinclusions)) return qs
class EmailDetailView(DetailView): """Show message open and error detail for an email address""" _prefetch_queryset = EmailCommunication.objects.select_related( "communication__foia__agency__jurisdiction", "from_email" ).prefetch_related( Prefetch("opens", queryset=EmailOpen.objects.select_related("recipient")), Prefetch("errors", queryset=EmailError.objects.select_related("recipient")), "to_emails", "cc_emails", ) queryset = EmailAddress.objects.prefetch_related( Prefetch("from_emails", queryset=_prefetch_queryset), Prefetch("to_emails", queryset=_prefetch_queryset), Prefetch("cc_emails", queryset=_prefetch_queryset), ) template_name = "communication/email_detail.html" pk_url_kwarg = "idx" context_object_name = "email_address" def get_context_data(self, **kwargs): """Add all email messages""" context = super(EmailDetailView, self).get_context_data(**kwargs) email_address = self.object context["emails"] = email_address.from_emails.union( email_address.to_emails.all(), email_address.cc_emails.all() ).order_by("sent_datetime") context["sidebar_admin_url"] = reverse( "admin:communication_emailaddress_change", args=(email_address.pk,) ) return context
def shared_ci(request): deleted = [] if request.user.is_authenticated() and request.user.has_perm( 'ref.change_component_instance'): deleted = ComponentInstance.objects.annotate(num_envt=Count('environments')).filter(~Q(num_envt=1), deleted=True).\ select_related('description').\ order_by('description__name', 'id') sec = (False, ) if request.user.is_authenticated() and request.user.has_perm( 'ref.allfields_componentinstance'): sec = (True, False) cis = ComponentInstance.objects.annotate(num_envt=Count('environments')).filter(~Q(num_envt=1), deleted=False).\ select_related('description').\ prefetch_related('environments').\ prefetch_related(Prefetch('field_set', queryset=ComponentInstanceField.objects.filter(field__widget_row__gte=0, field__sensitive__in=sec).order_by('field__widget_row', 'field__id'))).\ prefetch_related(Prefetch('description__field_set', queryset=ImplementationFieldDescription.objects.filter(widget_row__gte=0, sensitive__in=sec).order_by('widget_row', 'id'))).\ prefetch_related(Prefetch('description__computed_field_set', queryset=ImplementationComputedFieldDescription.objects.filter(widget_row__gte=0, sensitive__in=sec).order_by('widget_row', 'id'))).\ order_by('description__tag', 'description__name') return render(request, 'ref/envt_shared.html', { 'deleted': deleted, 'cis': cis })
def _retrieve_people(self, target_entity: Entity, filter: StickinessFilter, team: Team) -> ReturnDict: from posthog.api.person import PersonSerializer if target_entity.type == TREND_FILTER_TYPE_EVENTS: filtered_events = base.process_entity_for_events(target_entity, team_id=team.pk, order_by=None).filter( base.filter_events(team.pk, filter, target_entity) ) elif target_entity.type == TREND_FILTER_TYPE_ACTIONS: actions = Action.objects.filter(deleted=False, team=team) actions = actions.prefetch_related(Prefetch("steps", queryset=ActionStep.objects.order_by("id"))) try: actions.get(pk=target_entity.id) except Action.DoesNotExist: return PersonSerializer([], many=True).data filtered_events = base.process_entity_for_events(target_entity, team_id=team.pk, order_by=None).filter( base.filter_events(team.pk, filter, target_entity) ) else: raise ValueError("target entity must be action or event") events = ( filtered_events.values("person_id") .annotate(day_count=Count(filter.trunc_func("timestamp"), distinct=True)) .filter(day_count=filter.selected_interval) ) people = Person.objects.filter( team=team, id__in=[p["person_id"] for p in events[filter.offset : filter.offset + 100]], ) people = people.prefetch_related(Prefetch("persondistinctid_set", to_attr="distinct_ids_cache")) return PersonSerializer(people, many=True).data
def fetch_restaurants(self): self = self.prefetch_related( Prefetch('items', queryset=OrderItem.objects.select_related('product'))) orders = [] for order in self: order_items = set( [item.product.name for item in order.items.all()]) order.coord = get_coordinates(settings.YANDEX_API_KEY, order.address) restaurants = Restaurant.objects.all().prefetch_related( Prefetch('menu_items', queryset=RestaurantMenuItem.objects.select_related( 'product'))) order.restaurants = [] for restaurant in restaurants: menu_items = set([ item.product.name for item in restaurant.menu_items.all() if item.availability ]) if order_items.issubset(menu_items): restaurant.coord = get_coordinates(settings.YANDEX_API_KEY, restaurant.address) restaurant.distance = round( distance.distance(order.coord, restaurant.coord).km, 3) order.restaurants.append(restaurant) order.restaurants.sort(key=lambda place: place.distance) orders.append(order) return orders
def envt(request, envt_id): envt = Environment.objects.\ select_related('typology').\ get(pk=envt_id) deleted = [] if request.user.is_authenticated() and request.user.has_perm( 'ref.change_component_instance'): deleted = ComponentInstance.objects.filter(environments__id=envt_id, deleted=True).\ select_related('description').\ order_by('description__name', 'id') sec = (False, ) if not envt.protected or ( request.user.is_authenticated() and request.user.has_perm('ref.allfields_componentinstance')): sec = (True, False) cis = ComponentInstance.objects.filter(environments__id=envt_id, deleted=False).\ select_related('description').\ select_related('instanciates__implements__application').\ prefetch_related(Prefetch('field_set', queryset=ComponentInstanceField.objects.filter(field__widget_row__gte=0, field__sensitive__in=sec).order_by('field__widget_row', 'field__id'))).\ prefetch_related(Prefetch('description__field_set', queryset=ImplementationFieldDescription.objects.filter(widget_row__gte=0, sensitive__in=sec).order_by('widget_row', 'id'))).\ prefetch_related(Prefetch('description__computed_field_set', queryset=ImplementationComputedFieldDescription.objects.filter(widget_row__gte=0, sensitive__in=sec).order_by('widget_row', 'id'))).\ order_by('description__tag', 'description__name') return render(request, 'ref/envt.html', { 'envt': envt, 'deleted': deleted, 'cis': cis })
def preload(self, user, expand): """Preload relations""" from documentcloud.projects.models import Project queryset = self top_expands, nested_expands = split_levels(expand) all_expanded = "~all" in top_expands nested_default = "~all" if all_expanded else "" if "user" in top_expands or all_expanded: queryset = queryset.prefetch_related( Prefetch( "user", queryset=User.objects.preload( user, nested_expands.get("user", nested_default)), )) else: queryset = queryset.select_related("user") if "organization" in top_expands or all_expanded: queryset = queryset.select_related("organization") if "projects" in top_expands or all_expanded: projects = Project.objects.annotate_is_admin(user) else: projects = Project.objects.all() queryset = queryset.prefetch_related( Prefetch("projects", projects.get_viewable(user))) if "sections" in top_expands or all_expanded: queryset = queryset.prefetch_related("sections") return queryset
def get(self, request, *args, **kwargs): """[retreive UserCustomBS] 현재 유저의 Custom BS중에서 GET 방식으로 요청받은 title값을 통해 저장된 Custom BS 정보를 불러옴 Args: URL query : ...?title=입력받은title값 """ custom_title = request.GET["title"] if not custom_title: return Response({ 'message': "Recieve failed", }, status=status.HTTP_402_PAYMENT_REQUIRED) user = request.user.profile bs_queryset = UserCustomBS.objects\ .prefetch_related( Prefetch('fs_account', queryset=CustomFS_Account.objects.all()), Prefetch('fs_account__sub_account', queryset=CustomSUB_Account.objects.all()))\ .filter( Q(user=user) & Q(custom_title=custom_title) ) serializer = UserCustomBSSerializer(bs_queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
def annotate_documentations(klass: Union[Event, LessonPeriod, ExtraLesson], wanted_week: CalendarWeek, pks: List[int]) -> QuerySet: """Return an annotated queryset of all provided register objects.""" if isinstance(klass, LessonPeriod): prefetch = Prefetch( "documentations", queryset=LessonDocumentation.objects.filter(week=wanted_week.week, year=wanted_week.year), ) else: prefetch = Prefetch("documentations") instances = klass.objects.prefetch_related(prefetch).filter(pk__in=pks) if klass == LessonPeriod: instances = instances.annotate_week(wanted_week) elif klass in (LessonPeriod, ExtraLesson): instances = instances.order_by("period__weekday", "period__period") else: instances = instances.order_by("period_from__weekday", "period_from__period") instances = instances.annotate(has_documentation=Exists( LessonDocumentation.objects.filter( ~Q(topic__exact=""), week=wanted_week.week, year=wanted_week.year, ).filter(**{klass.label_: OuterRef("pk")}))) return instances
def prefetch_queryset(cls): """ Prefetch the related objects that will be serialized with a `Program`. We use Pefetch objects so that we can prefetch and select all the way down the chain of related fields from programs to course runs (i.e., we want control over the querysets that we're prefetching). """ return Program.objects.all().select_related('type', 'video', 'partner').prefetch_related( 'excluded_course_runs', 'expected_learning_items', 'faq', 'job_outlook_items', # `type` is serialized by a third-party serializer. Providing this field name allows us to # prefetch `applicable_seat_types`, a m2m on `ProgramType`, through `type`, a foreign key to # `ProgramType` on `Program`. 'type__applicable_seat_types', # We need the full Course prefetch here to get CourseRun information that methods on the Program # model iterate across (e.g. language). These fields aren't prefetched by the minimal Course serializer. Prefetch('courses', queryset=CourseSerializer.prefetch_queryset()), Prefetch('authoring_organizations', queryset=OrganizationSerializer.prefetch_queryset()), Prefetch('credit_backing_organizations', queryset=OrganizationSerializer.prefetch_queryset()), Prefetch('corporate_endorsements', queryset=CorporateEndorsementSerializer.prefetch_queryset()), Prefetch('individual_endorsements', queryset=EndorsementSerializer.prefetch_queryset()), )
def new_ci_step2(request, instance_id ): # always edit an existing CI - to create a CI use step 1. instance = ComponentInstance.objects.select_related('description', 'instanciates')\ .prefetch_related( Prefetch('field_set', ComponentInstanceField.objects.order_by('field__widget_row', 'field__name').select_related('field')), Prefetch('rel_target_set', ComponentInstanceRelation.objects.order_by('field__name').select_related('field')))\ .prefetch_related('environments', 'description__field_set', 'description__target_set').get(pk=instance_id) cls = form_for_model(instance.description) if request.POST: form = cls(request.POST, instance=instance) if form.is_valid(): form.save() # To where should we redirect? if 'submit_stay' in request.POST: return redirect('ref:edit_ci', instance_id=instance_id) if 'submit_toenvt' in request.POST: if len(form.cleaned_data['environments']) >= 1: return redirect( 'ref:envt', envt_id=form.cleaned_data['environments'][0].id) else: return redirect('ref:shared_ci') else: form = cls(instance=instance) return render_to_response("ref/instance_edit_step2.html", { 'form': form, 'descr': instance.description, 'instance': instance })
def data_dictionary_json(request, domain, case_type_name=None): props = [] fhir_resource_type_name_by_case_type = {} fhir_resource_prop_by_case_prop = {} queryset = CaseType.objects.filter(domain=domain).prefetch_related( Prefetch('properties', queryset=CaseProperty.objects.order_by('name')), Prefetch('properties__allowed_values', queryset=CasePropertyAllowedValue.objects.order_by('allowed_value')) ) if toggles.FHIR_INTEGRATION.enabled(domain): fhir_resource_type_name_by_case_type, fhir_resource_prop_by_case_prop = load_fhir_resource_mappings( domain) if case_type_name: queryset = queryset.filter(name=case_type_name) for case_type in queryset: p = { "name": case_type.name, "fhir_resource_type": fhir_resource_type_name_by_case_type.get(case_type), "properties": [], } for prop in case_type.properties.all(): p['properties'].append({ "description": prop.description, "fhir_resource_prop_path": fhir_resource_prop_by_case_prop.get(prop), "name": prop.name, "data_type": prop.data_type, "group": prop.group, "deprecated": prop.deprecated, "allowed_values": {av.allowed_value: av.description for av in prop.allowed_values.all()}, }) props.append(p) return JsonResponse({'case_types': props})
def get_queryset(self): return Company.objects.prefetch_related( Prefetch('contacts', queryset=Contact.objects.prefetch_related( Prefetch('orders'))), Prefetch('orders'), )
def detect_related_serializer_joins(cls): # Auto detects joins from Related Field Serializers if not hasattr(cls.__class__, '__{}__initialized'.format( cls.__name__)): setattr(cls.__class__, '__{}__initialized'.format(cls.__name__), True) if not hasattr(cls.Meta, 'joins'): setattr(cls.Meta, 'joins', []) klass = cls() for key in klass._readable_fields: serializer_fks = [] if issubclass(klass[key.field_name]._proxy_class, PrimaryKeyRelatedField): cls.Meta.joins.append(ForeignKeyJoin(key.source)) elif issubclass(klass[key.field_name]._proxy_class, ManyRelatedField): queryset = klass[key.field_name]._field.child_relation.queryset \ if klass[key.field_name]._field.child_relation.queryset else None if queryset: cls.Meta.joins.append( Prefetch(klass[key.field_name]._field.source, queryset=klass[key.field_name]._field. child_relation.queryset.select_related( *serializer_fks))) else: cls.Meta.joins.append( Prefetch(klass[key.field_name]._field.source)) else: class_ = klass[key.field_name]._proxy_class many = False if hasattr(klass[key.field_name]._field, 'many'): class_ = klass[key.field_name]._field.child.__class__ many = True if issubclass(class_, BaseSerializer): class_obj = class_() class_obj.detect_related_serializer_joins() if not many: cls.Meta.joins.append( ForeignKeyJoin(key.source, class_obj.Meta.joins)) else: serializer_fks = [] serializer_m2m = [] for x in class_obj.Meta.joins: if isinstance(x, ForeignKeyJoin): fks, prefetches = x.normalize_joins() serializer_fks += fks serializer_m2m += prefetches elif isinstance(x, Prefetch): serializer_m2m.append(x) cls.Meta.joins.append( Prefetch(klass[key.field_name].source, queryset=class_obj.Meta.model.objects. select_related( *serializer_fks).prefetch_related( *serializer_m2m)))
def prefetch_queryset(cls): return Course.objects.all().select_related('level_type', 'video', 'partner').prefetch_related( 'expected_learning_items', 'prerequisites', 'subjects', Prefetch('course_runs', queryset=CourseRunSerializer.prefetch_queryset()), Prefetch('authoring_organizations', queryset=OrganizationSerializer.prefetch_queryset()), Prefetch('sponsoring_organizations', queryset=OrganizationSerializer.prefetch_queryset()), )
def lc_versions(request, lc_id): lc = LogicalComponent.objects.select_related( 'application').prefetch_related( Prefetch( 'versions', queryset=LogicalComponentVersion.objects.prefetch_related( Prefetch( 'installed_by', queryset=InstallableItem.objects.all().select_related( 'belongs_to_set__backupset'))))).get(pk=lc_id) return render(request, 'scm/lc_versions_detail.html', {'lc': lc})
class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.prefetch_related( Prefetch( "memberships", queryset=Membership.objects.select_related("organization__plan"), ), Prefetch( "emailaddress_set", queryset=EmailAddress.objects.filter(primary=True), to_attr="primary_emails", ), ).order_by("created_at") permission_classes = (ScopePermission | IsAdminUser, ) read_scopes = ("read_user", ) write_scopes = ("write_user", ) lookup_field = "individual_organization_id" def get_serializer_class(self): # The only actions expected are create and retrieve # If we add other write actions, update this method if self.action == "create": return UserWriteSerializer else: return UserReadSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() headers = self.get_success_headers(serializer.data) setup_user_email(request, user, []) if not user.is_agency: email_address = EmailAddress.objects.get_primary(user) key = EmailConfirmationHMAC(email_address).key activate_url = reverse("account_confirm_email", args=[key]) send_mail( subject=_("Welcome to MuckRock"), template="account/email/email_confirmation_signup_message.html", user=user, extra_context={ "activate_url": activate_url, "minireg": True }, ) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def react_base(request, page): if not request.user.is_authenticated() or not can_read(request.user): data = { 'login_form': AuthenticationForm(request), 'static_version': STATIC_VERSION, 'is_debug': settings.DEBUG, } return render(request, 'login.html', data) houses = [] rooms = [] for house in House.objects.all().prefetch_related( Prefetch('rooms', queryset=Room.objects.all())): houses.append(serialize_house(house)) for room in house.rooms.all(): rooms.append(serialize_room(room)) request_data = { 'houses': houses, 'rooms': rooms, 'user': serialize_user(request.user) } data = { 'page': page, 'request_data': json.dumps(request_data), 'static_version': STATIC_VERSION, 'is_debug': settings.DEBUG, } return render(request, 'react_base.html', data)
def get_context_data(self, **kwargs): """Data for the explore page""" context = super(CrowdsourceExploreView, self).get_context_data(**kwargs) context[ 'crowdsource_users'] = CrowdsourceResponse.objects.get_user_count( ) context['crowdsource_data'] = CrowdsourceResponse.objects.count() context['crowdsource_count'] = Crowdsource.objects.exclude( status='draft').count() context['crowdsources'] = (Crowdsource.objects.annotate( user_count=Count('responses__user', distinct=True)).order_by( '-datetime_created').filter( status='open', project_only=False, featured=True, ).select_related( 'user', 'project', ).prefetch_related( 'data', Prefetch( 'responses', queryset=CrowdsourceResponse.objects.select_related( 'user__profile')), )[:5]) return context
def stickiness_process_entity_type(target_entity: Entity, team: Team, filter: StickinessFilter) -> QuerySet: events: Union[EventManager, QuerySet] = Event.objects.none() if target_entity.type == TREND_FILTER_TYPE_EVENTS: events = base.process_entity_for_events(target_entity, team_id=team.pk, order_by=None).filter( base.filter_events( team.pk, filter, target_entity)) elif target_entity.type == TREND_FILTER_TYPE_ACTIONS: actions = Action.objects.filter(deleted=False, team=team) actions = actions.prefetch_related( Prefetch("steps", queryset=ActionStep.objects.order_by("id"))) try: actions.get(pk=target_entity.id) except Action.DoesNotExist: return Event.objects.none() events = base.process_entity_for_events(target_entity, team_id=team.pk, order_by=None).filter( base.filter_events( team.pk, filter, target_entity)) else: raise ValueError("target entity must be action or event") return events
def _generate_data_for_export(domain, export_fhir_data): def generate_prop_dict(case_prop, fhir_resource_prop): prop_dict = { _('Case Property'): case_prop.name, _('Group'): case_prop.group, _('Data Type'): case_prop.data_type, _('Description'): case_prop.description, _('Deprecated'): case_prop.deprecated } if export_fhir_data: prop_dict[_('FHIR Resource Property')] = fhir_resource_prop return prop_dict queryset = CaseType.objects.filter(domain=domain).prefetch_related( Prefetch('properties', queryset=CaseProperty.objects.order_by('name'))) case_type_data = {} case_prop_data = {} fhir_resource_prop_by_case_prop = {} if export_fhir_data: fhir_resource_type_name_by_case_type, fhir_resource_prop_by_case_prop = load_fhir_resource_mappings( domain) _add_fhir_resource_mapping_sheet(case_type_data, fhir_resource_type_name_by_case_type) for case_type in queryset: case_prop_data[case_type.name or _("No Name")] = [ generate_prop_dict(prop, fhir_resource_prop_by_case_prop.get(prop)) for prop in case_type.properties.all() ] return case_type_data, case_prop_data
class PostViewSet(ModelViewSet): queryset = Post.objects.all().prefetch_related( Prefetch("comments", queryset=Comment.objects.order_by("-create_time"))) filterset_class = PostFilter serializer_class = PostSerializer renderer_classes = [ModelTemplateHTMLRenderer, JSONRenderer] permission_classes = [IsAuthenticatedOrReadOnly] ordering = ["-create_time"] def get_template_names(self) -> List[str]: if self.detail: return ["blog/posts_detail.html"] else: return ["blog/posts_list.html"] @action(detail=False, methods=["GET", "POST"], permission_classes=[IsAuthenticated]) def compose(self, request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() self.post_pk = form.instance.id return HttpResponseRedirect( reverse("post-detail", kwargs={"pk": self.post_pk})) else: form = PostForm() return render(request, "blog/posts_compose.html", {"form": form})
def query_set( self, init: Optional[QuerySet] = None) \ -> QuerySet: qs = self.ModelClass.objects \ if init is None \ else init if self.select_related: qs = qs.select_related(*self.select_related) qs = qs.only(*self.field_names) if self.order: if isinstance(self.order, (list, tuple)): qs = qs.order_by(*self.order) else: assert self.order is True else: qs = qs.order_by() if self.many_related_model_query_graphs: qs = qs.prefetch_related( *(Prefetch(lookup=many_related_field_name, queryset=many_related_model_query_graph.query_set()) for many_related_field_name, many_related_model_query_graph in self.many_related_model_query_graphs.items())) return qs
def run(self, filter: Filter, team: Team, *args, **kwargs) -> List[Dict[str, Any]]: actions = Action.objects.filter(team_id=team.pk).order_by("-id") if len(filter.actions) > 0: actions = Action.objects.filter( pk__in=[entity.id for entity in filter.actions], team_id=team.pk) actions = actions.prefetch_related( Prefetch("steps", queryset=ActionStep.objects.order_by("id"))) filter = self._set_default_dates(filter, team.pk) if filter.formula: return handle_compare(filter, self._run_formula_query, team) for entity in filter.entities: if entity.type == TREND_FILTER_TYPE_ACTIONS: try: entity.name = actions.get(id=entity.id).name except Action.DoesNotExist: return [] if len(filter.entities) == 1 or filter.compare: result = [] for entity in filter.entities: result.extend( handle_compare(filter, self._run_query, team, entity=entity)) else: result = self._run_parallel(filter, team) return result
def get_queryset(self, request): return (super().get_queryset(request).select_related( "doctype", ).prefetch_related( "tags", "languages", # Optimize lookup of fragments in two steps: prefetch_related on # TextBlock, then select_related on Fragment. # # prefetch_related works on m2m and generic relationships and # operates at the python level, while select_related only works # on fk or one-to-one and operates at the database level. We # can chain the latter onto the former because TextBlocks have # only one Fragment. # # For more, see: # https://docs.djangoproject.com/en/3.2/ref/models/querysets/#prefetch-related Prefetch( "textblock_set", queryset=TextBlock.objects.select_related( "fragment", "fragment__collection"), ), "footnotes__content__isnull", ).annotate(shelfmk_all=ArrayAgg( "textblock__fragment__shelfmark")).order_by("shelfmk_all"))
def get_people( self, filter: Filter, team_id: int, target_date: datetime, lifecycle_type: str, request: Request, limit: int = 100, ): event_query, event_params = LifecycleEventQuery( team_id=team_id, filter=filter).get_query() result = sync_execute( LIFECYCLE_PEOPLE_SQL.format(events_query=event_query, interval_expr=filter.interval), { **event_params, "status": lifecycle_type, "target_date": target_date, "offset": filter.offset, "limit": limit, }, ) people = get_persons_by_uuids(team_id=team_id, uuids=[p[0] for p in result]) people = people.prefetch_related( Prefetch("persondistinctid_set", to_attr="distinct_ids_cache")) from posthog.api.person import PersonSerializer return PersonSerializer(people, many=True).data
def _export_data_dictionary(domain): queryset = CaseType.objects.filter(domain=domain).prefetch_related( Prefetch('properties', queryset=CaseProperty.objects.order_by('name'))) export_data = {} for case_type in queryset: export_data[case_type.name or _("No Name")] = [{ _('Case Property'): prop.name, _('Group'): prop.group, _('Data Type'): prop.data_type, _('Description'): prop.description, _('Deprecated'): prop.deprecated } for prop in case_type.properties.all()] headers = (_('Case Property'), _('Group'), _('Data Type'), _('Description'), _('Deprecated')) outfile = io.BytesIO() writer = Excel2007ExportWriter() header_table = [(tab_name, [headers]) for tab_name in export_data] writer.open(header_table=header_table, file=outfile) for tab_name, tab in export_data.items(): tab_rows = [] for row in tab: tab_rows.append([row.get(header, '') for header in headers]) writer.write([(tab_name, tab_rows)]) writer.close() return outfile
def items_to_index(cls): """Custom logic for finding items to be indexed when indexing in bulk.""" # NOTE: some overlap with prefetching used for django admin return ( Document.objects.select_related("doctype") .prefetch_related( "tags", "languages", "footnotes", "footnotes__source", "footnotes__source__authorship", "footnotes__source__authorship__creator", "footnotes__source__source_type", "footnotes__source__languages", "log_entries", Prefetch( "textblock_set", queryset=TextBlock.objects.select_related( "fragment", "fragment__collection" ), ), ) .distinct() )
def get(self, request, *args, **kwargs): if not request.user.is_authenticated: return JsonResponse({ 'Status': False, 'Error': 'Log in required' }, status=status.HTTP_403_FORBIDDEN) if request.user.type != 'shop': return JsonResponse( { 'Status': False, 'Error': 'Только для магазинов' }, status=status.HTTP_403_FORBIDDEN) items = Prefetch( 'ordered_items', queryset=OrderItem.objects.filter(shop__user_id=request.user.id)) order = Order.objects.filter( ordered_items__shop__user_id=request.user.id).exclude(state='basket').\ prefetch_related(items).select_related('contact').annotate( total_sum=Sum('ordered_items__total_amount'), total_quantity=Sum('ordered_items__quantity')) serializer = OrderSerializer(order, many=True) return Response(serializer.data)