Python django.db.models 模块,Prefetch() 实例源码

我们从Python开源项目中,提取了以下43个代码示例,用于说明如何使用django.db.models.Prefetch()

项目:PrivacyScore    作者:PrivacyScore    | 项目源码 | 文件源码
def scan_scan_list(request: HttpRequest, scan_list_id: int) -> HttpResponse:
    """Schedule the scan of a scan list."""
    scan_list = get_object_or_404(
        ScanList.objects.prefetch_related(Prefetch(
            'sites',
            queryset=Site.objects.select_related('last_scan') \
                .annotate_most_recent_scan_start() \
                .annotate_most_recent_scan_end_or_null())
        ), pk=scan_list_id)
    was_any_site_scannable = scan_list.scan()
    if was_any_site_scannable:
        num_scanning_sites = Scan.objects.filter(end__isnull=True).count()
        messages.success(request,
            _("Scans for this list have been scheduled. "+ \
              "The total number of sites in the scanning queue "+ \
              "is %i (including yours)." % num_scanning_sites))
    else:
        messages.warning(request,
            _('All sites have been scanned recently. Please wait 30 minutes and try again.'))

    return redirect(reverse('frontend:view_scan_list', args=(scan_list_id,)))
项目:django-timeseries    作者:anthonyalmarza    | 项目源码 | 文件源码
def prefetch_latest(self, *related_names):
        """
            Exposes the latest associated reverse relation.

            Adds a query per related name.
        """
        prefetch_set = []
        for related_name in set(related_names):
            rev_rel = get_reverse_relation(self.model, related_name)

            field_name = rev_rel.field.name
            RelatedModel = rev_rel.field.model

            attr_name = 'latest_{}'.format(related_name)
            prefetch = Prefetch(
                related_name,
                queryset=RelatedModel.objects.filter(
                    **{field_name + '__in': self}
                ).order_by(field_name, '-created').distinct(field_name),
                to_attr=attr_name
            )
            prefetch_set.append(prefetch)
            self.latest_registry.add(attr_name)

        return self.prefetch_related(*prefetch_set)
项目:Hoshimori_Project    作者:kokonguyen191    | 项目源码 | 文件源码
def get_queryset(self, queryset, parameters, request):
            if request.user.is_authenticated():
                queryset = queryset.extra(select={
                    'followed': 'SELECT COUNT(*) FROM magi_userpreferences_following WHERE userpreferences_id = {} AND user_id = auth_user.id'.format(
                        request.user.preferences.id),
                })
                queryset = queryset.extra(select={
                    'is_followed_by': 'SELECT COUNT(*) FROM magi_userpreferences_following WHERE userpreferences_id = (SELECT id FROM magi_userpreferences WHERE user_id = auth_user.id) AND user_id = {}'.format(
                        request.user.id),
                })
            queryset = queryset.extra(select={
                'total_following': 'SELECT COUNT(*) FROM magi_userpreferences_following WHERE userpreferences_id = (SELECT id FROM magi_userpreferences WHERE user_id = auth_user.id)',
                'total_followers': 'SELECT COUNT(*) FROM magi_userpreferences_following WHERE user_id = auth_user.id',
            })
            queryset = queryset.select_related('preferences', 'favorite_character1', 'favorite_character2',
                                               'favorite_character3')
            from django.db.models import Prefetch
            from magi.models import UserLink
            queryset = queryset.prefetch_related(Prefetch('accounts', to_attr='all_accounts'),
                                                 Prefetch('links', queryset=UserLink.objects.order_by('-i_relevance'),
                                                          to_attr='all_links'))
            return queryset
项目:Hoshimori_Project    作者:kokonguyen191    | 项目源码 | 文件源码
def extra_context(self, context):
            request = context['request']
            if request.user.is_authenticated():
                context['collection'] = 'collection' in request.GET
                if context['collection']:
                    request.user.all_accounts = request.user.accounts.all().prefetch_related(
                        Prefetch('ownedcards',
                                 queryset=OwnedCard.objects.filter(card_id=context['item'].id).order_by(
                                     '-card__i_rarity', 'card__student_id'), to_attr='all_owned'),
                    )
                    # Set values to avoid using select_related since we already have them
                    for account in request.user.all_accounts:
                        account.owner = request.user
                        for oc in account.all_owned:
                            oc.card = context['item']
                            oc.is_mine = True
            return context
项目:db0.company    作者:db0company    | 项目源码 | 文件源码
def social(request):
    context = globalContext(request)
    context['socials'] = models.SocialLink.objects.all().order_by('small', '-importance', 'name')
    context['show_tags'] = 'show_tags' in request.GET
    if context['show_tags']:
        context['socials'] = context['socials'].prefetch_related(Prefetch('tags', to_attr='all_tags'))
    if 'tags' in request.GET:
        context['hide_nav'] = True
        context['back'] = '/socialtags/'
        context['tags'] = []
        for tag in request.GET['tags'].split(','):
            context['tags'].append(tag)
            context['socials'] = context['socials'].filter(tags__name=tag)
        if not context['socials']:
            context['tags'] = []
        context['tags'] = ' - '.join(context['tags'])
    for (link, color) in zip(context['socials'], utils.getRainbowFromSize(len(context['socials']))):
        link.color = color
        if context['show_tags']:
            link.tags_string = u', '.join([tag.name for tag in link.all_tags])
    return render(request, 'social.html', context)
项目:django_postgres_extensions    作者:primal100    | 项目源码 | 文件源码
def test_m2m(self):
        # Control lookups.
        with self.assertNumQueries(2):
            lst1 = self.traverse_qs(
                Person.objects.prefetch_related('houses'),
                [['houses']]
            )

        # Test lookups.
        with self.assertNumQueries(2):
            lst2 = self.traverse_qs(
                Person.objects.prefetch_related(Prefetch('houses')),
                [['houses']]
            )
        self.assertEqual(lst1, lst2)
        with self.assertNumQueries(2):
            lst2 = self.traverse_qs(
                Person.objects.prefetch_related(Prefetch('houses', to_attr='houses_lst')),
                [['houses_lst']]
            )
        self.assertEqual(lst1, lst2)
项目:django_postgres_extensions    作者:primal100    | 项目源码 | 文件源码
def test_reverse_m2m(self):
        # Control lookups.
        with self.assertNumQueries(2):
            lst1 = self.traverse_qs(
                House.objects.prefetch_related('occupants'),
                [['occupants']]
            )

        # Test lookups.
        with self.assertNumQueries(2):
            lst2 = self.traverse_qs(
                House.objects.prefetch_related(Prefetch('occupants')),
                [['occupants']]
            )
        self.assertEqual(lst1, lst2)
        with self.assertNumQueries(2):
            lst2 = self.traverse_qs(
                House.objects.prefetch_related(Prefetch('occupants', to_attr='occupants_lst')),
                [['occupants_lst']]
            )
        self.assertEqual(lst1, lst2)
项目:django_postgres_extensions    作者:primal100    | 项目源码 | 文件源码
def test_m2m_through_fk(self):
        # Control lookups.
        with self.assertNumQueries(3):
            lst1 = self.traverse_qs(
                Room.objects.prefetch_related('house__occupants'),
                [['house', 'occupants']]
            )

        # Test lookups.
        with self.assertNumQueries(3):
            lst2 = self.traverse_qs(
                Room.objects.prefetch_related(Prefetch('house__occupants')),
                [['house', 'occupants']]
            )
        self.assertEqual(lst1, lst2)
        with self.assertNumQueries(3):
            lst2 = self.traverse_qs(
                Room.objects.prefetch_related(Prefetch('house__occupants', to_attr='occupants_lst')),
                [['house', 'occupants_lst']]
            )
        self.assertEqual(lst1, lst2)
项目:django_postgres_extensions    作者:primal100    | 项目源码 | 文件源码
def test_m2m_through_gfk(self):
        TaggedItem.objects.create(tag="houses", content_object=self.house1)
        TaggedItem.objects.create(tag="houses", content_object=self.house2)

        # Control lookups.
        with self.assertNumQueries(3):
            lst1 = self.traverse_qs(
                TaggedItem.objects.filter(tag='houses').prefetch_related('content_object__rooms'),
                [['content_object', 'rooms']]
            )

        # Test lookups.
        with self.assertNumQueries(3):
            lst2 = self.traverse_qs(
                TaggedItem.objects.prefetch_related(
                    Prefetch('content_object'),
                    Prefetch('content_object__rooms', to_attr='rooms_lst')
                ),
                [['content_object', 'rooms_lst']]
            )
        self.assertEqual(lst1, lst2)
项目:django_postgres_extensions    作者:primal100    | 项目源码 | 文件源码
def test_traverse_single_item_property(self):
        # Control lookups.
        with self.assertNumQueries(5):
            lst1 = self.traverse_qs(
                Person.objects.prefetch_related(
                    'houses__rooms',
                    'primary_house__occupants__houses',
                ),
                [['primary_house', 'occupants', 'houses']]
            )

        # Test lookups.
        with self.assertNumQueries(5):
            lst2 = self.traverse_qs(
                Person.objects.prefetch_related(
                    'houses__rooms',
                    Prefetch('primary_house__occupants', to_attr='occupants_lst'),
                    'primary_house__occupants_lst__houses',
                ),
                [['primary_house', 'occupants_lst', 'houses']]
            )
        self.assertEqual(lst1, lst2)
项目:django_postgres_extensions    作者:primal100    | 项目源码 | 文件源码
def test_traverse_multiple_items_property(self):
        # Control lookups.
        with self.assertNumQueries(4):
            lst1 = self.traverse_qs(
                Person.objects.prefetch_related(
                    'houses',
                    'all_houses__occupants__houses',
                ),
                [['all_houses', 'occupants', 'houses']]
            )

        # Test lookups.
        with self.assertNumQueries(4):
            lst2 = self.traverse_qs(
                Person.objects.prefetch_related(
                    'houses',
                    Prefetch('all_houses__occupants', to_attr='occupants_lst'),
                    'all_houses__occupants_lst__houses',
                ),
                [['all_houses', 'occupants_lst', 'houses']]
            )
        self.assertEqual(lst1, lst2)
项目:django-strict    作者:kyle-eshares    | 项目源码 | 文件源码
def test_queryset_methods2(data):
    prefetch = Prefetch('books', to_attr='prefetched_books')
    author_qs = Author.objects.prefetch_related(prefetch).all()
    author_list = author_qs.to_list()

    for author in author_list:
        assert len(author.prefetched_books) == 2
项目:django-strict    作者:kyle-eshares    | 项目源码 | 文件源码
def prefetch_related(self, *lookups):
        for lookup in lookups:
            if not isinstance(lookup, Prefetch):
                raise PrefetchExpected()
            if lookup.to_attr is None:
                raise PrefetchAttrUndefined()
        return super(StrictQuerySet, self).prefetch_related(*lookups)

    # # # # # # # # #
    # Added Methods #
    # # # # # # # # #
项目:PrivacyScore    作者:PrivacyScore    | 项目源码 | 文件源码
def prefetch_columns(self) -> 'ScanListQuerySet':
        return self.prefetch_related(
            Prefetch(
                'columns',
                queryset=ListColumn.objects.order_by('sort_key'),
                to_attr='sorted_columns'))
项目:PrivacyScore    作者:PrivacyScore    | 项目源码 | 文件源码
def prefetch_tags(self) -> 'ScanListQuerySet':
        return self.prefetch_related(
            Prefetch(
                'tags',
                queryset=ListTag.objects.order_by('name'),
                to_attr='ordered_tags'))
项目:PrivacyScore    作者:PrivacyScore    | 项目源码 | 文件源码
def prefetch_column_values(self, scan_list: ScanList) -> 'SiteQuerySet':
        return self.prefetch_related(Prefetch(
                'column_values',
                queryset=ListColumnValue.objects.filter(
                    column__scan_list=scan_list).order_by(
                    'column__sort_key'),
                to_attr='ordered_column_values')
        )
项目:Dota2-EU-Ladder    作者:UncleVasya    | 项目源码 | 文件源码
def get_queryset(self):
        qs = super(PlayerList, self).get_queryset()

        season = LadderSettings.get_solo().current_season
        qs = qs.filter(matchplayer__match__season=season).distinct()\
            .prefetch_related(Prefetch(
                'matchplayer_set',
                queryset=MatchPlayer.objects.select_related('match'),
                to_attr='matches'
            ))
        return qs
项目:Dota2-EU-Ladder    作者:UncleVasya    | 项目源码 | 文件源码
def get_queryset(self):
        qs = super(PlayersSuccessful, self).get_queryset()

        season = LadderSettings.get_solo().current_season
        qs = qs.filter(matchplayer__match__season=season).distinct()\
            .prefetch_related(Prefetch(
                'matchplayer_set',
                queryset=MatchPlayer.objects.select_related('match'),
                to_attr='matches'
            ))
        return qs
项目:Dota2-EU-Ladder    作者:UncleVasya    | 项目源码 | 文件源码
def add_matches_data(self):
        player = self.object

        player.matches = player.matches.select_related(
            'scorechange'
        ).prefetch_related(
            Prefetch('match__matchplayer_set',
                     queryset=MatchPlayer.objects.select_related('player'))
        )
项目:Dota2-EU-Ladder    作者:UncleVasya    | 项目源码 | 文件源码
def get_queryset(self):
        qs = super(MatchList, self).get_queryset()

        season = LadderSettings.get_solo().current_season
        qs = qs.filter(matchplayer__match__season=season).distinct()\
            .prefetch_related(Prefetch(
                'matchplayer_set',
                queryset=MatchPlayer.objects.select_related('match')
            ))
        return qs
项目:BanGDream    作者:MagiCircles    | 项目源码 | 文件源码
def get_queryset(self, queryset, parameters, request):
            queryset = super(EventCollection.ItemView, self).get_queryset(queryset, parameters, request)
            queryset = queryset.select_related('main_card', 'secondary_card').prefetch_related(Prefetch('boost_members', to_attr='all_members'), Prefetch('gachas', to_attr='all_gachas'), Prefetch('gift_songs', to_attr='all_gifted_songs'))
            return queryset
项目:BanGDream    作者:MagiCircles    | 项目源码 | 文件源码
def get_queryset(self, queryset, parameters, request):
            queryset = super(GachaCollection.ItemView, self).get_queryset(queryset, parameters, request)
            queryset = queryset.select_related('event').prefetch_related(Prefetch('cards', to_attr='all_cards'))
            return queryset
项目:munch-core    作者:crunchmail    | 项目源码 | 文件源码
def get_queryset(self, with_statuses=True):
        qs = super().get_queryset()
        if with_statuses:
            status_qs = MailStatus.objects.order_by(
                'mail', '-creation_date').distinct('mail')
            qs = qs.prefetch_related(Prefetch(
                'statuses', queryset=status_qs, to_attr='last_status_cached'))
        return qs
项目:munch-core    作者:crunchmail    | 项目源码 | 文件源码
def get_queryset(self):
        return Contact.objects.all().prefetch_related(Prefetch(
            'contact_list',
            queryset=ContactList.objects.all().only('contact_fields')))
项目:hydra    作者:Our-Revolution    | 项目源码 | 文件源码
def get_queryset(self, request):
        return super(EventPromotionRequestAdmin, self).get_queryset(request).prefetch_related(Prefetch('event', Event.objects.all()), Prefetch('host', Constituent.objects.all()), Prefetch('event__event_type', EventType.objects.all()))
项目:FinSL-signbank    作者:Signbank    | 项目源码 | 文件源码
def gloss_list_xml(self, dataset):
    """Returns all entries in dictionarys idgloss fields in XML form that is supported by ELAN"""
    # http://www.mpi.nl/tools/elan/EAFv2.8.xsd
    dataset = Dataset.objects.get(id=dataset)
    return serialize_glosses(dataset,
                             Gloss.objects.filter(dataset=dataset)
                             .prefetch_related(
                                 Prefetch('translation_set', queryset=Translation.objects.filter(gloss__dataset=dataset)
                                          .select_related('keyword', 'language')),
                                 Prefetch('glosstranslations_set', queryset=GlossTranslations.objects.
                                          filter(gloss__dataset=dataset).select_related('language'))))
项目:db0.company    作者:db0company    | 项目源码 | 文件源码
def project(request, id):
    context = globalContext(request)
    context['hide_nav'] = True
    context['back'] = '/projects/'
    context['project'] = get_object_or_404(models.Project.objects.all().prefetch_related(Prefetch('stats', to_attr='all_stats'), Prefetch('tags', to_attr='all_tags')), id=id)
    total = len(context['project'].all_stats)
    context['percent_stats'] = 100 / int(total / int(math.ceil(total / 4))) if total else 0
    return render(request, 'project.html', context)
项目:c3nav    作者:c3nav    | 项目源码 | 文件源码
def register_changed_geometries(self):
        from c3nav.mapdata.models.geometry.space import SpaceGeometryMixin
        query = self.groups.all()
        for model in get_submodels(SpecificLocation):
            related_name = model._meta.default_related_name
            subquery = model.objects.all()
            if issubclass(model, SpaceGeometryMixin):
                subquery = subquery.select_related('space')
            query.prefetch_related(Prefetch('groups__'+related_name, subquery))

        for group in query:
            group.register_changed_geometries(do_query=False)
项目:c3nav    作者:c3nav    | 项目源码 | 文件源码
def optimize_query(qs):
    if issubclass(qs.model, SpecificLocation):
        base_qs = LocationGroup.objects.select_related('category')
        qs = qs.prefetch_related(Prefetch('groups', queryset=base_qs))
    return qs
项目:c3nav    作者:c3nav    | 项目源码 | 文件源码
def prefetch_related(self, *lookups):
        """
        We split up all prefetch related lookups into one-level prefetches
        and convert them into Prefetch() objects with custom querysets.
        This makes sure that the prefetch also happens on the virtually modified database.
        """
        lookups_qs = {tuple(lookup.prefetch_through.split('__')): lookup.queryset for lookup in lookups
                      if isinstance(lookup, Prefetch) and lookup.queryset is not None}
        for qs in lookups_qs.values():
            if not isinstance(qs, QuerySetWrapper):
                raise TypeError('Prefetch object queryset needs to be wrapped!')
        lookups = tuple((lookup.prefetch_through if isinstance(lookup, Prefetch) else lookup) for lookup in lookups)

        lookups_splitted = tuple(tuple(lookup.split('__')) for lookup in lookups)
        max_depth = max(len(lookup) for lookup in lookups_splitted)
        lookups_by_depth = []
        for i in range(max_depth):
            lookups_by_depth.append(set(tuple(lookup[:i+1] for lookup in lookups_splitted if len(lookup) > i)))

        lookup_models = {(): self._obj.model}
        lookup_querysets = {(): self.all()}
        for depth_lookups in lookups_by_depth:
            for lookup in depth_lookups:
                model = lookup_models[lookup[:-1]]._meta.get_field(lookup[-1]).related_model
                lookup_models[lookup] = model
                lookup_querysets[lookup] = lookups_qs.get(lookup, self._wrap_model(model).objects.all())

        for depth_lookups in reversed(lookups_by_depth):
            for lookup in depth_lookups:
                qs = lookup_querysets[lookup]
                prefetch = Prefetch(lookup[-1], qs)
                lower_qs = lookup_querysets[lookup[:-1]]
                lower_qs._obj = lower_qs._obj.prefetch_related(prefetch)

        return lookup_querysets[()]
项目:omb-eregs    作者:18F    | 项目源码 | 文件源码
def optimize(queryset):
    """To avoid the "n+1" query problem, we will optimize our querysets by
    either joining 1-to-1 relations (via select_related) or ensuring a single
    query for many-to-many relations (via prefetch_related)."""
    footnote_prefetch = Prefetch(
        'footnotecitations',
        queryset=FootnoteCitation.objects.select_related('footnote_node'),
    )
    requirement_prefetch = Prefetch(
        'inlinerequirements',
        queryset=InlineRequirement.objects.select_related('requirement'),
    )
    return queryset.\
        prefetch_related(footnote_prefetch, 'cites', 'externallinks',
                         requirement_prefetch)
项目:edd    作者:JBEI    | 项目源码 | 文件源码
def _do_export(self, tables):
        from main.models import Assay, Line, Measurement, MeasurementValue, Protocol, Study
        # add data from each exported measurement; already sorted by protocol
        value_qs = MeasurementValue.objects.select_related('updated').order_by('x')
        measures = self.selection.measurements.prefetch_related(
            Prefetch('measurementvalue_set', queryset=value_qs, to_attr='pf_values'),
            Prefetch('assay__line__strains'),
            Prefetch('assay__line__carbon_source'),
        )
        print("-----|||||----- Queried Measurement 2")
        for measurement in measures:
            assay = measurement.assay
            protocol = assay.protocol
            line = assay.line
            if self.options.line_section:
                line_only = [Line, Study, ]
                other_only = [Assay, Measurement, Protocol, ]
                # add row to line table w/ Study, Line columns only
                if line.id not in tables['line']:
                    row = self._output_row_with_measure(measurement, models=line_only)
                    tables['line'][line.id] = row
                # create row for protocol/all table w/ Protocol, Assay, Measurement columns only
                row = self._output_row_with_measure(measurement, models=other_only)
            else:
                # create row for protocol/all table
                row = self._output_row_with_measure(measurement)
            table, table_key = self._init_tables_for_protocol(tables, protocol)
            values = measurement.pf_values  # prefetched above
            if self.options.layout == ExportOption.DATA_COLUMN_BY_POINT:
                for value in values:
                    arow = row[:]
                    arow.append(value_str(value.x))
                    arow.append(value_str(value.y))
                    table[value.id] = arow
            else:
                # keep track of all x values encountered in the table
                xx = self._x_values[table_key] = self._x_values.get(table_key, {})
                # do value_str to the float-casted version of x to eliminate 0-padding
                xx.update({value_str(v.x): v.x for v in values})
                squashed = {value_str(v.x): value_str(v.y) for v in values}
                row.append(squashed)
                table[measurement.id] = row
项目:MagiCircles    作者:MagiCircles    | 项目源码 | 文件源码
def _userItemFilterQuerySet(queryset, parameters, request):
    if request.user.is_authenticated():
        queryset = queryset.extra(select={
            'followed': 'SELECT COUNT(*) FROM web_userpreferences_following WHERE userpreferences_id = {} AND user_id = auth_user.id'.format(request.user.preferences.id),
        })
        queryset = queryset.extra(select={
            'is_followed_by': 'SELECT COUNT(*) FROM web_userpreferences_following WHERE userpreferences_id = (SELECT id FROM web_userpreferences WHERE user_id = auth_user.id) AND user_id = {}'.format(request.user.id),
        })
    queryset = queryset.extra(select={
        'total_following': 'SELECT COUNT(*) FROM web_userpreferences_following WHERE userpreferences_id = (SELECT id FROM web_userpreferences WHERE user_id = auth_user.id)',
        'total_followers': 'SELECT COUNT(*) FROM web_userpreferences_following WHERE user_id = auth_user.id',
    })
    queryset = queryset.select_related('preferences', 'favorite_character1', 'favorite_character2', 'favorite_character3')
    queryset = queryset.prefetch_related(Prefetch('accounts', to_attr='all_accounts'), Prefetch('links', to_attr='all_links'))
    return queryset
项目:django_postgres_extensions    作者:primal100    | 项目源码 | 文件源码
def test_prefetch_object(self):
        book1 = Book.objects.get(id=self.book1.id)
        with self.assertNumQueries(1):
            prefetch_related_objects([book1], Prefetch('authors'))

        with self.assertNumQueries(0):
            self.assertEqual(set(book1.authors.all()), {self.author1, self.author2, self.author3})
项目:django_postgres_extensions    作者:primal100    | 项目源码 | 文件源码
def test_prefetch_object_to_attr(self):
        book1 = Book.objects.get(id=self.book1.id)
        with self.assertNumQueries(1):
            prefetch_related_objects([book1], Prefetch('authors', to_attr='the_authors'))

        with self.assertNumQueries(0):
            self.assertEqual(set(book1.the_authors), {self.author1, self.author2, self.author3})
项目:django_postgres_extensions    作者:primal100    | 项目源码 | 文件源码
def test_prefetch_queryset(self):
        book1 = Book.objects.get(id=self.book1.id)
        with self.assertNumQueries(1):
            prefetch_related_objects(
                [book1],
                Prefetch('authors', queryset=Author.objects.filter(id__in=[self.author1.id, self.author2.id]))
            )

        with self.assertNumQueries(0):
            self.assertEqual(set(book1.authors.all()), {self.author1, self.author2})
项目:django_postgres_extensions    作者:primal100    | 项目源码 | 文件源码
def test_forward_m2m_to_attr_conflict(self):
        msg = 'to_attr=authors conflicts with a field on the Book model.'
        authors = Author.objects.all()
        with self.assertRaisesMessage(ValueError, msg):
            list(Book.objects.prefetch_related(
                Prefetch('authors', queryset=authors, to_attr='authors'),
            ))
        # Without the ValueError, an author was deleted due to the implicit
        # save of the relation assignment.
        self.assertEqual(self.book1.authors.count(), 3)
项目:django_postgres_extensions    作者:primal100    | 项目源码 | 文件源码
def test_reverse_m2m_to_attr_conflict(self):
        msg = 'to_attr=books conflicts with a field on the Author model.'
        poems = Book.objects.filter(title='Poems')
        with self.assertRaisesMessage(ValueError, msg):
            list(Author.objects.prefetch_related(
                Prefetch('books', queryset=poems, to_attr='books'),
            ))
        # Without the ValueError, a book was deleted due to the implicit
        # save of reverse relation assignment.
        self.assertEqual(self.author1.books.count(), 2)
项目:django_postgres_extensions    作者:primal100    | 项目源码 | 文件源码
def test_o2m_through_m2m(self):
        # Control lookups.
        with self.assertNumQueries(3):
            lst1 = self.traverse_qs(
                Person.objects.prefetch_related('houses', 'houses__rooms'),
                [['houses', 'rooms']]
            )

        # Test lookups.
        with self.assertNumQueries(3):
            lst2 = self.traverse_qs(
                Person.objects.prefetch_related(Prefetch('houses'), 'houses__rooms'),
                [['houses', 'rooms']]
            )
        self.assertEqual(lst1, lst2)
        with self.assertNumQueries(3):
            lst2 = self.traverse_qs(
                Person.objects.prefetch_related(Prefetch('houses'), Prefetch('houses__rooms')),
                [['houses', 'rooms']]
            )
        self.assertEqual(lst1, lst2)
        with self.assertNumQueries(3):
            lst2 = self.traverse_qs(
                Person.objects.prefetch_related(Prefetch('houses', to_attr='houses_lst'), 'houses_lst__rooms'),
                [['houses_lst', 'rooms']]
            )
        self.assertEqual(lst1, lst2)
        with self.assertNumQueries(3):
            lst2 = self.traverse_qs(
                Person.objects.prefetch_related(
                    Prefetch('houses', to_attr='houses_lst'),
                    Prefetch('houses_lst__rooms', to_attr='rooms_lst')
                ),
                [['houses_lst', 'rooms_lst']]
            )
        self.assertEqual(lst1, lst2)
项目:django_postgres_extensions    作者:primal100    | 项目源码 | 文件源码
def test_nested_prefetch_related_are_not_overwritten(self):
        # Regression test for #24873
        houses_2 = House.objects.prefetch_related(Prefetch('rooms'))
        persons = Person.objects.prefetch_related(Prefetch('houses', queryset=houses_2))
        houses = House.objects.prefetch_related(Prefetch('occupants', queryset=persons))
        list(houses)  # queryset must be evaluated once to reproduce the bug.
        self.assertEqual(
            houses.all()[0].occupants.all()[0].houses.all()[1].rooms.all()[0],
            self.room2_1
        )
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def dashboard(request):
    current_role_count = request.roles.count()
    if current_role_count == 1:
        current_role = request.roles[0]
        role_type = request.roles[0].group.name
        if role_type == "Unassigned":
            raise PermissionDenied()
        if role_type == "Site Supervisor":
            return HttpResponseRedirect(reverse("fieldsight:site-dashboard", kwargs={'pk': current_role.site.pk}))
        if role_type == "Reviewer":
            return HttpResponseRedirect(reverse("fieldsight:site-dashboard", kwargs={'pk': current_role.site.pk}))
        if role_type == "Project Manager":
            return HttpResponseRedirect(reverse("fieldsight:project-dashboard", kwargs={'pk': current_role.project.pk}))
        if role_type == "Organization Admin":
            return HttpResponseRedirect(reverse("fieldsight:organizations-dashboard",
                                                kwargs={'pk': current_role.organization.pk}))
    if current_role_count > 1:
        return HttpResponseRedirect(reverse("fieldsight:roles-dashboard"))

    total_users = User.objects.all().count()
    total_organizations = Organization.objects.all().count()
    total_projects = Project.objects.all().count()
    total_sites = Site.objects.all().count()
    data = serialize('custom_geojson', Site.objects.prefetch_related('site_instances').filter(is_survey=False, is_active=True), geometry_field='location', fields=('name', 'public_desc', 'additional_desc', 'address', 'location', 'phone','id'))


    # outstanding_query = FInstance.objects.filter(form_status=0)
    # data = serialize('custom_geojson', Site.objects.filter(is_survey=False, is_active=True).prefetch_related(Prefetch('site_instances', queryset=outstanding_query, to_attr='outstanding')), geometry_field='location', fields=('name', 'public_desc', 'additional_desc', 'address', 'location', 'phone','id'))
    # fs_forms = FieldSightXF.objects.all()
    # fs_forms = list(fs_forms)
    # # outstanding = flagged = approved = rejected = 0
    # for form in fs_forms:
    #     if form.form_status == 0:
    #         outstanding += 1
    #     elif form.form_status == 1:
    #         flagged +=1
    #     elif form.form_status == 2:
    #         approved +=1
    #     else:
    #         rejected +=1

    dashboard_data = {
        'total_users': total_users,
        'total_organizations': total_organizations,
        'total_projects': total_projects,
        'total_sites': total_sites,
        # 'outstanding': outstanding,
        # 'flagged': flagged,
        # 'approved': approved,
        # 'rejected': rejected,
        'data': data,
    }
    return TemplateResponse(request, "fieldsight/fieldsight_dashboard.html", dashboard_data)
项目:FinSL-signbank    作者:Signbank    | 项目源码 | 文件源码
def get_queryset(self):
        # Get queryset
        qs = super(GlossListPublicView, self).get_queryset()
        get = self.request.GET

        # Exclude datasets that are not public.
        qs = qs.exclude(dataset__is_public=False)
        # Exclude glosses that are not 'published'.
        qs = qs.exclude(published=False)

        if 'lang' in get and get['lang'] != '' and get['lang'] != 'all':
            signlang = get.get('lang')
            qs = qs.filter(dataset__signlanguage__language_code_3char=signlang)

        # Search for multiple datasets (if provided)
        vals = get.getlist('dataset', [])
        if vals != []:
            qs = qs.filter(dataset__in=vals)

        if 'search' in get and get['search'] != '':
            val = get['search']
            # Filters
            qs = qs.filter(Q(idgloss__istartswith=val) | Q(translation__keyword__text__istartswith=val)
                           # | Q(idgloss_en__icontains=val) # idgloss_en not shown in results, therefore removed.
                           )

        qs = qs.distinct()

        # Set order according to GET field 'order'
        if 'order' in get:
            qs = qs.order_by(get['order'])
        else:
            qs = qs.order_by('idgloss')

        # Prefetching translation and dataset objects for glosses to minimize the amount of database queries.
        qs = qs.prefetch_related(Prefetch('translation_set', queryset=Translation.objects.filter(
            language__language_code_2char__iexact=get_language()).select_related('keyword')),
                                 Prefetch('glosstranslations_set', queryset=GlossTranslations.objects.filter(
                                     language__language_code_2char__iexact=get_language())),
                                 Prefetch('dataset'),
                                 # Ordering by version to get the first versions posterfile.
                                 Prefetch('glossvideo_set', queryset=GlossVideo.objects.all().order_by('version')))
        return qs
项目:FinSL-signbank    作者:Signbank    | 项目源码 | 文件源码
def get_queryset(self):
        # get query terms from self.request
        qs = GlossRelation.objects.all()

        # Filter in only objects in the datasets the user has permissions to.
        allowed_datasets = get_objects_for_user(self.request.user, 'dictionary.view_dataset')
        qs = qs.filter(source__dataset__in=allowed_datasets).filter(target__dataset__in=allowed_datasets)

        get = self.request.GET

        # Search for multiple datasets (if provided)
        vals = get.getlist('dataset', [])
        if vals != []:
            qs = qs.filter(source__dataset__in=vals).filter(target__dataset__in=vals)

        if 'search' in get and get['search'] != '':
            val = get['search']
            # Searches for multiple fields at the same time. Looking if any of the fields match.
            query = (Q(source__idgloss__icontains=val) | Q(target__idgloss__icontains=val))
            qs = qs.filter(query)

        if 'source' in get and get['source'] != '':
            val = get['source']
            # Search for sources glosses starting with a string, case sensitive
            query = Q(source__idgloss__istartswith=val)
            qs = qs.filter(query)

        if 'target' in get and get['target'] != '':
            val = get['target']
            # Search for sources glosses starting with a string, case sensitive
            query = Q(target__idgloss__istartswith=val)
            qs = qs.filter(query)

        # Prefetching translation and dataset objects for glosses to minimize the amount of database queries.
        qs = qs.prefetch_related(Prefetch('source__dataset'), Prefetch('target__dataset'))

        # Set order according to GET field 'order'
        if 'order' in get:
            qs = qs.order_by(get['order'])
        else:
            qs = qs.order_by('source')
        return qs