def test_order_by_relation_with_different_ordering(self):
        """
        Apply order_by() with a field that returns a model with different
        ordering on sub-QuerySets.
        """
        # Both of these have publishers with the same fields, but different
        # ordering.
        all = QuerySetSequence(Article.objects.all(), BlogPost.objects.all())

        # Order by publisher and ensure it takes.
        qss = all.order_by('publisher')
        self.assertEqual(qss.query.order_by, ['publisher'])

        self.assertRaises(FieldError, list, qss)
    def test_duplicates(self):
        """Ensure that pagination works over an 'extreme' number of duplicates."""
        PAGES = 100 # This must be unique from other fixture data.

        # Create a bunch of books that are the same.
        for i in range(15):
            book = Book.objects.create(title=str(i),
                                       author=self.author,
                                       publisher=self.publisher,
                                       pages=PAGES)

        # And use only those duplicate books.
        self.queryset = QuerySetSequence(Book.objects.filter(pages=PAGES))

        titles = [item.title for item in self.queryset]

        # Look at both the pages (which should all be 1) and the IDs.
        next_url = '/'
        for i in range(3):
            request = Request(factory.get(next_url))
            queryset = self.pagination.paginate_queryset(self.queryset, request)
            titles, pages = zip(*[(item.title, item.pages) for item in queryset])

            self.assertEqual(titles, tuple(map(lambda d: str(d + (i * 5)), [0, 1, 2, 3, 4])))
            self.assertEqual(pages, (PAGES, ) * 5)

            next_url = self.pagination.get_next_link()

        self.assertIsNone(next_url)
    def setUp(self):
        self.author = Author.objects.create(name="Jane Doe")
        self.publisher = Publisher.objects.create(name="Pablo's Publishing",
                                                  address="123 Publishing Street")

        for d in range(1, 15):
            book = Book.objects.create(title='Book %s' % (d % 2),
                                       author=self.author,
                                       publisher=self.publisher,
                                       pages=d)

        self.pagination = _TestPagination()
        self.queryset = QuerySetSequence(Book.objects.filter(pages__lte=7),
                                         Book.objects.filter(pages__gt=7))
    def test_validate(self):
        # Create an option to select
        fixture = TModel.objects.create(name=self.id())

        # Instanciate the form with the fixture selected
        form = TForm(
            http.QueryDict('name=%s&test=%s' %
                           (self.id(), self.get_value(fixture))))

        # Remove the option from field queryset choices
        form.fields['test'].queryset = QuerySetSequence(
            TModel.objects.exclude(pk=fixture.pk))

        # Form should not validate
        self.assertFalse(form.is_valid())
    def get_queryset(self):

        playlists = Playlist.objects.all()

        if self.q:
            playlists = playlists.filter(title__icontains=self.q)

        qs = autocomplete.QuerySetSequence(playlists, )

        if self.q:
            qs = qs.filter(title__icontains=self.q)

        querysets = list(qs.get_querysets())
        qs = QuerySetSequence(*[q for q in querysets])

        return qs
    def setUpClass(cls):
        """Set-up some data to be tested against."""
        alice = Author.objects.create(name="Alice")
        bob = Author.objects.create(name="Bob")

        # Purposefully ordered such that the pks will be in the opposite order
        # than the names.
        mad_magazine = PeriodicalPublisher.objects.create(name="Mad Magazine")
        # This publisher is unused, just takes up a PK in the database.
        Publisher.objects.create(name="Unused Publisher")
        big_books = Publisher.objects.create(name="Big Books",
                                             address="123 Street")
        wacky_website = OnlinePublisher.objects.create(name="Wacky Website")

        # Alice wrote some articles.
        Article.objects.create(title="Django Rocks",
                               author=alice,
                               publisher=mad_magazine)
        Article.objects.create(title="Alice in Django-land",
                               author=alice,
                               publisher=mad_magazine)

        # Bob wrote a couple of books, an article, and a blog post.
        Book.objects.create(title="Fiction",
                            author=bob,
                            publisher=big_books,
                            pages=10)
        Book.objects.create(title="Biography",
                            author=bob,
                            publisher=big_books,
                            pages=20)
        Article.objects.create(title="Some Article",
                               author=bob,
                               publisher=mad_magazine)
        BlogPost.objects.create(title="Post",
                                author=bob,
                                publisher=wacky_website)

        # Save the authors and publishers for later.
        cls.alice = alice
        cls.bob = bob
        cls.big_books = big_books
        cls.mad_magazine = mad_magazine
        cls.wacky_website = wacky_website

        # Many tests start with the same QuerySetSequence.
        cls.all = QuerySetSequence(Book.objects.all(), Article.objects.all())
    def get_queryset(self):
        queryset_models = []
        if self.q:
            for model, filter_value in self.model_choice:
                kwargs = {'{}__icontains'.format(filter_value): self.q}
                queryset_models.append(model.objects.filter(**kwargs))
        else:
            queryset_models = [
                model[0].objects.all() for model in self.model_choice
            ]

        # Aggregate querysets
        qs = QuerySetSequence(*queryset_models)

        # This will limit each queryset so that they show an equal number
        # of results.
        qs = self.mixup_querysets(qs)

        return qs
Beispiel #8
0
    def __init__(self, *args, model_choice=None, field_id=None, **kwargs):
        """
        :param args:
        :param model_choice: [(Model, 'filter_by', [('forwardfield_name', 'filter_by')]), ],
        List of tuples, for each select2 widget. Model is the model to query, 'filter_by' the attribute of the model
        to apply the filter.
        The list in the tuple is optional, its to forward a field from the form to the widget.
        :param field_id: Optional name instead of the automatic one
        :param kwargs:
        """
        self.field_id = field_id if field_id else id(self)
        if model_choice:
            self.model_choice = model_choice
            models_queryset = [
                model[0].objects.all() for model in model_choice
            ]
            kwargs['queryset'] = QuerySetSequence(*models_queryset)

        super().__init__(*args, **kwargs)
Beispiel #9
0
    def get_queryset(self):
        genes = Gene.objects.all()
        chemicals = Chemical.objects.exclude(categories__id=51).all()
        diseases = DiseaseTrait.objects.all()
        snps = Snp.objects.all()
        healtheffects = HealthEffect.objects.all()
        experiments = Identification.objects.all()

        if self.q:
            genes = genes.filter(name__icontains=self.q)
            chemicals = chemicals.filter(name__icontains=self.q)
            diseases = diseases.filter(name__icontains=self.q)
            snps = snps.filter(rsid__icontains=self.q)
            healtheffects = healtheffects.filter(name__icontains=self.q)
            experiments = experiments.filter(name__icontains=self.q)

        qs = QuerySetSequence(genes, chemicals, diseases, snps, healtheffects,
                              experiments)
        qs = self.mixup_querysets(qs)
        return qs
Beispiel #10
0
def list_all(request):
	if request.session.get('session_initialized') != 'true':
		request = set_session(request)
		redirect('/')

	if request.POST:
		request = update_session(request)
		if request.POST.get("cleartags") == 'true':
			return HttpResponseRedirect(redirect_to='/')
		redirect('/')
	queryset = list()
	todos = Todo.objects.all() if request.session.get('todos') == 'true' else None
	notes = Note.objects.all() if request.session.get('notes') == 'true' else None
	bookmarks = Bookmark.objects.all() if request.session.get('bookmarks') == 'true' else None
	tag_quantities = get_tags_count()

	if request.GET.get("tags"):
		disable_item_filtering(request)
		request.session['active_tag'] = request.GET.get("tags")
		if todos is not None:
			todos = todos.filter(tags__name__in=[request.GET.get("tags")])
		if notes is not None:
			notes = notes.filter(tags__name__in=[request.GET.get("tags")])
		if bookmarks is not None:
			bookmarks = bookmarks.filter(tags__name__in=[request.GET.get("tags")])

	for item in [todos, notes, bookmarks]:
		if item is not None:
			queryset.append(item)

	all_items = QuerySetSequence(*queryset). \
		order_by('-date_created' if request.session.get('sortbycreation') == 'true' else 'date_created'). \
		filter(Q(name__contains=request.session.get('search')) | Q(description__contains=request.session.get('search')))

	paginator = Paginator(all_items, 3)

	site = "index.html" if request.session.get('toggle_viewtype') == 'false' else "index-table.html"
	return render(request, site, context={
		"page_obj": paginator.get_page(request.GET.get('page')),
		"tag_quantities": tag_quantities,
		"active_tag": request.session['active_tag']})
Beispiel #11
0
 def get_querysets(self, linked_type=None):
     qss = list()
     if not linked_type:
         for link_name, linked_model in getattr(self.linkable, "_LINKS", dict()).items():
             if hasattr(self.linkable, link_name):
                 if hasattr(linked_model.model, 'authorization') and self.user is not None:
                     qss.append(
                         linked_model.model.authorization.for_user(self.user, self.permission).filter(
                             **{linked_model.reverse_link_name: self.linkable.pk}))
                 else:
                     qss.append(getattr(self.linkable, link_name).all())
     else:
         if not isinstance(linked_type, (list, tuple)):
             linked_type = [linked_type,]
         for link_name, linked_model in getattr(self.linkable, "_LINKS", dict()).items():
             if linked_type.count(linked_model.model) > 0:
                 if hasattr(linked_model.model, 'authorization') and self.user is not None:
                     qss.append(
                         linked_model.model.authorization.for_user(self.user, self.permission).filter(
                             **{linked_model.reverse_link_name: self.linkable.pk}))
                 else:
                     qss.append(getattr(self.linkable, link_name).all())
     return QuerySetSequence(*qss)
Beispiel #12
0
    def __init__(self, *args, **kwargs):
        """Initialize GenericForeignKeyModelField."""
        model_choice = kwargs.pop('model_choice', None)
        widget = kwargs.pop('widget', None)
        view = kwargs.pop('view', None)
        field_id = kwargs.pop('field_id', None)
        self.field_id = field_id if field_id else id(self)
        if model_choice:
            self.model_choice = model_choice
            models_queryset = [
                model[0].objects.all() for model in model_choice
            ]
            kwargs['queryset'] = QuerySetSequence(*models_queryset)

        # check if they are classes
        if isinstance(widget, type) and isinstance(view, type):
            self.widget_obj = widget
            self.view_obj = view
        else:
            raise AttributeError(
                "Class object are required (not instantiated)")

        super(GenericForeignKeyModelField, self).__init__(*args, **kwargs)
    def get_queryset(self):
        """Return queryset."""
        queryset_models = []
        for model_args in self.model_choice:
            model = model_args[0]
            filter_value = model_args[1]

            kwargs_model = {
                '{}__icontains'.format(filter_value): self.q if self.q else ''
            }
            forward_filtered = [Q(**kwargs_model)]

            try:
                forward_fields = model_args[2]
                for forward in forward_fields:
                    field_key = '{}__icontains'.format(forward[1])
                    field_value = self.forwarded[forward[0]]
                    forward_filtered.append(Q(**{field_key: field_value}))
            except IndexError:
                # if no list on the 3rd index of self.model_choice
                # (reserved for forwarding fields)
                pass

            # link the diffrent field by an & query
            and_forward_filtered = reduce(lambda x, y: x & y, forward_filtered)

            queryset_models.append(model.objects.filter(and_forward_filtered))

        # Aggregate querysets
        qs = QuerySetSequence(*queryset_models)

        # This will limit each queryset so that they show an equal number
        # of results.
        qs = self.mixup_querysets(qs)

        return qs
    def test_empty_subqueryset(self):
        qss = QuerySetSequence(Book.objects.all(),
                               Article.objects.none()).order_by('title')

        data = [it.title for it in qss]
        self.assertEqual(data, ['Biography', 'Fiction'])
 def _get_qss(self):
     """Returns a QuerySetSequence with 3 QuerySets."""
     return QuerySetSequence(Book.objects.all(), Article.objects.all(),
                             BlogPost.objects.all())
 def test_related_model(self):
     qss = QuerySetSequence(Article.objects.all(), BlogPost.objects.all())
     self.assertTrue(qss.filter(publisher__name="Wacky Website").exists())
 def test_empty(self):
     qss = QuerySetSequence()
     self.assertEqual(list(qss), [])
 def test_related_model(self):
     qss = QuerySetSequence(Article.objects.all(), BlogPost.objects.all())
     self.assertTrue(qss.filter(publisher__name="Wacky Website").exists())
Beispiel #19
0
 def setUpClass(cls):
     """Set-up some data to be tested against."""
     cls.qss = QuerySetSequence(Article.objects.all())
class TestSequenceCursorPagination(TestCase):
    """
    Unit tests for `queryset_sequence.pagination.SequenceCursorPagination`.

    Heavily based on `tests.test_pagination` from Django REST Framework.
    """

    PAGE_1 = [1, 2, 3, 4, 5]
    PAGE_2 = [6, 7, 8, 9, 10]
    PAGE_3 = [11, 12, 13, 14]

    def setUp(self):
        self.author = Author.objects.create(name="Jane Doe")
        self.publisher = Publisher.objects.create(name="Pablo's Publishing",
                                                  address="123 Publishing Street")

        for d in range(1, 15):
            book = Book.objects.create(title='Book %s' % (d % 2),
                                       author=self.author,
                                       publisher=self.publisher,
                                       pages=d)

        self.pagination = _TestPagination()
        self.queryset = QuerySetSequence(Book.objects.filter(pages__lte=7),
                                         Book.objects.filter(pages__gt=7))

    def get_pages(self, url):
        """
        Given a URL return a tuple of:
        (previous page, current page, next page, previous url, next url)
        """
        request = Request(factory.get(url))
        queryset = self.pagination.paginate_queryset(self.queryset, request)
        current = [item.pages for item in queryset]

        next_url = self.pagination.get_next_link()
        previous_url = self.pagination.get_previous_link()

        if next_url is not None:
            request = Request(factory.get(next_url))
            queryset = self.pagination.paginate_queryset(self.queryset, request)
            next = [item.pages for item in queryset]
        else:
            next = None

        if previous_url is not None:
            request = Request(factory.get(previous_url))
            queryset = self.pagination.paginate_queryset(self.queryset, request)
            previous = [item.pages for item in queryset]
        else:
            previous = None

        return (previous, current, next, previous_url, next_url)

    def test_ordering(self):
        """Ensure that the QuerySetSequence is ordered as expected."""
        pages = [b.pages for b in self.queryset]
        self.assertEqual(pages, self.PAGE_1 + self.PAGE_2 + self.PAGE_3)

        # The first 7 are in the 0th list, the last 7 are in the 1st list.
        number = [getattr(b, '#') for b in self.queryset]
        self.assertEqual(number, [0] * 7 + [1] * 7)

    def test_invalid_cursor(self):
        request = Request(factory.get('/', {'cursor': '123'}))
        with self.assertRaises(exceptions.NotFound):
            self.pagination.paginate_queryset(self.queryset, request)

    def test_use_with_ordering_filter(self):
        class MockView:
            filter_backends = (filters.OrderingFilter,)
            ordering_fields = ['title', 'author']
            ordering = 'title'

        request = Request(factory.get('/', {'ordering': 'author'}))
        ordering = self.pagination.get_ordering(request, [], MockView())
        self.assertEqual(ordering, ('#', 'author',))

        request = Request(factory.get('/', {'ordering': '-author'}))
        ordering = self.pagination.get_ordering(request, [], MockView())
        self.assertEqual(ordering, ('#', '-author',))

        request = Request(factory.get('/', {'ordering': 'invalid'}))
        ordering = self.pagination.get_ordering(request, [], MockView())
        self.assertEqual(ordering, ('#', 'title',))

    def test_cursor_pagination(self):
        (previous, current, next, previous_url, next_url) = self.get_pages('/')

        self.assertIsNone(previous)
        self.assertEqual(current, self.PAGE_1)
        self.assertEqual(next, self.PAGE_2)

        (previous, current, next, previous_url, next_url) = self.get_pages(next_url)

        self.assertEqual(previous, self.PAGE_1)
        self.assertEqual(current, self.PAGE_2)
        self.assertEqual(next, self.PAGE_3)

        (previous, current, next, previous_url, next_url) = self.get_pages(next_url)

        self.assertEqual(previous, self.PAGE_2)
        self.assertEqual(current, self.PAGE_3)
        self.assertIsNone(next)

    def test_cursor_stableness(self):
        """
        Test what happens if we remove domains after loading a page.
        Pages should be independent, i.e. a cursor points to a particular
        domain, and shouldn't affect offsets.
        """
        (previous, current, next, previous_url, next_url) = self.get_pages('/')

        # The first page is as normal.
        self.assertIsNone(previous)
        self.assertEqual(current, self.PAGE_1)
        self.assertEqual(next, self.PAGE_2)

        # Delete Books, this shouldn't affect the next request.
        Book.objects.filter(pages__lte=3).delete()
        Book.objects.filter(pages__gte=13).delete()

        (previous, current, next, _, old_next_url) = self.get_pages(next_url)

        # Should be some missing items
        self.assertEqual(previous, [4, 5])
        self.assertEqual(current, self.PAGE_2)
        self.assertEqual(next, [11, 12])

        # Deleting some from the current page and reloading should have the page
        # offset.
        Book.objects.get(pages=7).delete()

        (previous, current, next, _, new_next_url) = self.get_pages(next_url)

        # Should be some missing items
        self.assertEqual(previous, [4, 5])
        self.assertEqual(current, [6, 8, 9, 10, 11])
        self.assertEqual(next, [12])

        # The next_url returned with the different items missing will actually
        # be different.
        self.assertNotEqual(old_next_url, new_next_url)

    def test_multiple_ordering(self):
        """Test a Pagination with multiple items in the ordering attribute."""

        # This will order by:
        #   1. Even pages
        #   2. Odd pages
        #   3. Both of the above will be done in increasing order.
        #   4. Ordering happens for 1 - 7, then 8 - 14.
        class TestPagination(_TestPagination):
            ordering = ['title', 'pages']

        self.pagination = TestPagination()

        PAGE_1 = [2, 4, 6, 1, 3]
        PAGE_2 = [5, 7, 8, 10, 12]
        PAGE_3 = [14, 9, 11, 13]

        # Check that the ordering is as expected.
        pages = [b.pages for b in self.queryset.order_by('#', *self.pagination.ordering)]
        self.assertEqual(pages, PAGE_1 + PAGE_2 + PAGE_3)

        # Now perform pretty much the same test as test_cursor_pagination, but
        # the ordering will be different.
        (previous, current, next, previous_url, next_url) = self.get_pages('/')

        self.assertIsNone(previous)
        self.assertEqual(current, PAGE_1)
        self.assertEqual(next, PAGE_2)

        (previous, current, next, previous_url, next_url) = self.get_pages(next_url)

        self.assertEqual(previous, PAGE_1)
        self.assertEqual(current, PAGE_2)
        self.assertEqual(next, PAGE_3)

        (previous, current, next, previous_url, next_url) = self.get_pages(next_url)

        self.assertEqual(previous, PAGE_2)
        self.assertEqual(current, PAGE_3)
        self.assertIsNone(next)

    def test_duplicates(self):
        """Ensure that pagination works over an 'extreme' number of duplicates."""
        PAGES = 100 # This must be unique from other fixture data.

        # Create a bunch of books that are the same.
        for i in range(15):
            book = Book.objects.create(title=str(i),
                                       author=self.author,
                                       publisher=self.publisher,
                                       pages=PAGES)

        # And use only those duplicate books.
        self.queryset = QuerySetSequence(Book.objects.filter(pages=PAGES))

        titles = [item.title for item in self.queryset]

        # Look at both the pages (which should all be 1) and the IDs.
        next_url = '/'
        for i in range(3):
            request = Request(factory.get(next_url))
            queryset = self.pagination.paginate_queryset(self.queryset, request)
            titles, pages = zip(*[(item.title, item.pages) for item in queryset])

            self.assertEqual(titles, tuple(map(lambda d: str(d + (i * 5)), [0, 1, 2, 3, 4])))
            self.assertEqual(pages, (PAGES, ) * 5)

            next_url = self.pagination.get_next_link()

        self.assertIsNone(next_url)
Beispiel #21
0
class TestSequenceCursorPagination(TestCase):
    """
    Unit tests for `queryset_sequence.pagination.SequenceCursorPagination`.

    Heavily based on `tests.test_pagination` from Django REST Framework.
    """

    PAGE_1 = [1, 2, 3, 4, 5]
    PAGE_2 = [6, 7, 8, 9, 10]
    PAGE_3 = [11, 12, 13, 14]

    def setUp(self):
        self.author = Author.objects.create(name="Jane Doe")
        self.publisher = Publisher.objects.create(name="Pablo's Publishing",
                                                  address="123 Publishing Street")

        for d in range(1, 15):
            Book.objects.create(title='Book %s' % (d % 2),
                                author=self.author,
                                publisher=self.publisher,
                                pages=d,
                                release=date(2018, 10, 5))

        self.pagination = _TestPagination()
        self.queryset = QuerySetSequence(Book.objects.filter(pages__lte=7),
                                         Book.objects.filter(pages__gt=7))

    def get_pages(self, url):
        """
        Given a URL return a tuple of:
        (previous page, current page, next page, previous url, next url)
        """
        request = Request(factory.get(url))
        queryset = self.pagination.paginate_queryset(self.queryset, request)
        current = [item.pages for item in queryset]

        next_url = self.pagination.get_next_link()
        previous_url = self.pagination.get_previous_link()

        if next_url is not None:
            request = Request(factory.get(next_url))
            queryset = self.pagination.paginate_queryset(self.queryset, request)
            next = [item.pages for item in queryset]
        else:
            next = None

        if previous_url is not None:
            request = Request(factory.get(previous_url))
            queryset = self.pagination.paginate_queryset(self.queryset, request)
            previous = [item.pages for item in queryset]
        else:
            previous = None

        return (previous, current, next, previous_url, next_url)

    def test_ordering(self):
        """Ensure that the QuerySetSequence is ordered as expected."""
        pages = [b.pages for b in self.queryset]
        self.assertEqual(pages, self.PAGE_1 + self.PAGE_2 + self.PAGE_3)

        # The first 7 are in the 0th list, the last 7 are in the 1st list.
        number = [getattr(b, '#') for b in self.queryset]
        self.assertEqual(number, [0] * 7 + [1] * 7)

    def test_invalid_cursor(self):
        request = Request(factory.get('/', {'cursor': '123'}))
        with self.assertRaises(exceptions.NotFound):
            self.pagination.paginate_queryset(self.queryset, request)

    def test_use_with_ordering_filter(self):
        class MockView:
            filter_backends = (filters.OrderingFilter,)
            ordering_fields = ['title', 'author']
            ordering = 'title'

        request = Request(factory.get('/', {'ordering': 'author'}))
        ordering = self.pagination.get_ordering(request, [], MockView())
        self.assertEqual(ordering, ('#', 'author',))

        request = Request(factory.get('/', {'ordering': '-author'}))
        ordering = self.pagination.get_ordering(request, [], MockView())
        self.assertEqual(ordering, ('#', '-author',))

        request = Request(factory.get('/', {'ordering': 'invalid'}))
        ordering = self.pagination.get_ordering(request, [], MockView())
        self.assertEqual(ordering, ('#', 'title',))

    def test_cursor_pagination(self):
        """Ensure that the cursor properly flips through pages."""
        # Check the first page.
        (previous, current, next, previous_url, next_url) = self.get_pages('/')

        self.assertIsNone(previous)
        self.assertEqual(current, self.PAGE_1)
        self.assertEqual(next, self.PAGE_2)

        # Check the second page.
        (previous, current, next, previous_url, next_url) = self.get_pages(next_url)

        self.assertEqual(previous, self.PAGE_1)
        self.assertEqual(current, self.PAGE_2)
        self.assertEqual(next, self.PAGE_3)

        # Check the third page.
        (previous, current, next, previous_url, next_url) = self.get_pages(next_url)

        self.assertEqual(previous, self.PAGE_2)
        self.assertEqual(current, self.PAGE_3)
        self.assertIsNone(next)

    def test_cursor_stableness(self):
        """
        Test what happens if we remove domains after loading a page.
        Pages should be independent, i.e. a cursor points to a particular
        domain, and shouldn't affect offsets.
        """
        (previous, current, next, previous_url, next_url) = self.get_pages('/')

        # The first page is as normal.
        self.assertIsNone(previous)
        self.assertEqual(current, self.PAGE_1)
        self.assertEqual(next, self.PAGE_2)

        # Delete Books, this shouldn't affect the next request.
        Book.objects.filter(pages__lte=3).delete()
        Book.objects.filter(pages__gte=13).delete()

        (previous, current, next, _, old_next_url) = self.get_pages(next_url)

        # Should be some missing items
        self.assertEqual(previous, [4, 5])
        self.assertEqual(current, self.PAGE_2)
        self.assertEqual(next, [11, 12])

        # Deleting some from the current page and reloading should have the page
        # offset.
        Book.objects.get(pages=7).delete()

        (previous, current, next, _, new_next_url) = self.get_pages(next_url)

        # Should be some missing items
        self.assertEqual(previous, [4, 5])
        self.assertEqual(current, [6, 8, 9, 10, 11])
        self.assertEqual(next, [12])

        # The next_url returned with the different items missing will actually
        # be different.
        self.assertNotEqual(old_next_url, new_next_url)

    def test_multiple_ordering(self):
        """Test a Pagination with multiple items in the ordering attribute."""

        # This will order by:
        #   1. Even pages
        #   2. Odd pages
        #   3. Both of the above will be done in increasing order.
        #   4. Ordering happens for 1 - 7, then 8 - 14.
        class TestPagination(_TestPagination):
            ordering = ['title', 'pages']

        self.pagination = TestPagination()

        PAGE_1 = [2, 4, 6, 1, 3]
        PAGE_2 = [5, 7, 8, 10, 12]
        PAGE_3 = [14, 9, 11, 13]

        # Check that the ordering is as expected.
        pages = [b.pages for b in self.queryset.order_by('#', *self.pagination.ordering)]
        self.assertEqual(pages, PAGE_1 + PAGE_2 + PAGE_3)

        # Now perform pretty much the same test as test_cursor_pagination, but
        # the ordering will be different.
        (previous, current, next, previous_url, next_url) = self.get_pages('/')

        self.assertIsNone(previous)
        self.assertEqual(current, PAGE_1)
        self.assertEqual(next, PAGE_2)

        (previous, current, next, previous_url, next_url) = self.get_pages(next_url)

        self.assertEqual(previous, PAGE_1)
        self.assertEqual(current, PAGE_2)
        self.assertEqual(next, PAGE_3)

        (previous, current, next, previous_url, next_url) = self.get_pages(next_url)

        self.assertEqual(previous, PAGE_2)
        self.assertEqual(current, PAGE_3)
        self.assertIsNone(next)

    def test_duplicates(self):
        """Ensure that pagination works over an 'extreme' number of duplicates."""
        PAGES = 100 # This must be unique from other fixture data.

        # Create a bunch of books that are the same.
        for i in range(15):
            Book.objects.create(title=str(i),
                                author=self.author,
                                publisher=self.publisher,
                                pages=PAGES,
                                release=date(2018, 10, 5))

        # And use only those duplicate books.
        self.queryset = QuerySetSequence(Book.objects.filter(pages=PAGES))

        titles = [item.title for item in self.queryset]

        # Look at both the pages (which should all be 1) and the IDs.
        next_url = '/'
        for i in range(3):
            request = Request(factory.get(next_url))
            queryset = self.pagination.paginate_queryset(self.queryset, request)
            titles, pages = zip(*[(item.title, item.pages) for item in queryset])

            self.assertEqual(titles, tuple(map(lambda d: str(d + (i * 5)), [0, 1, 2, 3, 4])))
            self.assertEqual(pages, (PAGES, ) * 5)

            next_url = self.pagination.get_next_link()

        self.assertIsNone(next_url)
Beispiel #22
0
class HomeList(ListView):
    queryset = QuerySetSequence(Subject.objects.all(),
                                Embed.objects.all()).order_by('-created_at')
    paginate_by = 20
    context_object_name = 'aktywnosci'
    template_name = 'boards/board_list.html'
 def test_related_model(self):
     qss = QuerySetSequence(Article.objects.all(), BlogPost.objects.all())
     post = qss.get(publisher__name="Wacky Website")
     self.assertEqual(post.title, 'Post')
     self.assertIsInstance(post, BlogPost)
Beispiel #24
0
def get_game_participants(game: Game):
    players = Player.objects.filter(game=game, active=True)
    mods = Moderator.objects.filter(game=game, active=True)
    spectators = Spectator.objects.filter(game=game, active=True)

    return QuerySetSequence(players, mods, spectators)
 def test_related_model(self):
     qss = QuerySetSequence(Article.objects.all(), BlogPost.objects.all())
     post = qss.get(publisher__name="Wacky Website")
     self.assertEqual(post.title, 'Post')
     self.assertIsInstance(post, BlogPost)
Beispiel #26
0
def list_all(request):
    SESSION_INITIALIZED = "session_initialized"
    TODOS = "todos"
    NOTES = "notes"
    BOOKMARKS = "bookmarks"
    TAGS = "tags"
    TOGGLE_VIEWTYPE = "toggle_viewtype"
    ACTIVE_TAG = "active_tag"
    CLEAR_TAGS = "cleartags"
    SORT_BY_CREATION = "sortbycreation"
    SEARCH = "search"
    RESET = "reset"
    TRUE = "true"
    FALSE = "false"
    if request.session.get(SESSION_INITIALIZED) != TRUE:
        for var in [TODOS, NOTES, BOOKMARKS, SORT_BY_CREATION]:
            request.session[var] = TRUE
        for var in [TOGGLE_VIEWTYPE]:
            request.session[var] = FALSE
        for var in [SEARCH, ACTIVE_TAG]:
            request.session[var] = ""
        request.session[SESSION_INITIALIZED] = TRUE
        redirect("/")

    if request.POST:
        """Handle main items (todos, notes etc.)"""
        if request.POST.get(TODOS):
            request.session[TODOS] = request.POST.get(TODOS)
        if request.POST.get(NOTES):
            request.session[NOTES] = request.POST.get(NOTES)
        if request.POST.get(BOOKMARKS):
            request.session[BOOKMARKS] = request.POST.get(BOOKMARKS)
        """ Toggle viewtype"""
        if request.POST.get(TOGGLE_VIEWTYPE):
            request.session[TOGGLE_VIEWTYPE] = request.POST.get(
                TOGGLE_VIEWTYPE)
        """ Sorting handling """
        if request.POST.get(SORT_BY_CREATION) == TRUE:
            request.session[SORT_BY_CREATION] = request.POST.get(
                SORT_BY_CREATION)
        elif request.POST.get(SORT_BY_CREATION) == FALSE:
            request.session[SORT_BY_CREATION] = FALSE
        """ Handle search, tags, reset and clearing tags """
        if request.POST.get(SEARCH):
            if len(request.POST.get(SEARCH)) > 0:
                request.session[SEARCH] = request.POST.get(SEARCH)
            else:
                request.session[SEARCH] = ""
        # else:
        #     request.session[SEARCH] = ""

        if request.POST.get(RESET) == TRUE:
            request.session[SEARCH] = ""

        if request.POST.get(CLEAR_TAGS) == TRUE:
            request.session[ACTIVE_TAG] = ""
            return HttpResponseRedirect(redirect_to="/")

        redirect("/")
    """ List view of items """
    queryset = list()
    todos = Todo.objects.all() if request.session.get(TODOS) == TRUE else None
    notes = Note.objects.all() if request.session.get(NOTES) == TRUE else None
    bookmarks = Bookmark.objects.all() if request.session.get(
        BOOKMARKS) == TRUE else None
    tag_quantities = get_tags_count()

    if request.GET.get(TAGS):
        for var in [TODOS, NOTES, BOOKMARKS]:
            request.session[var] = TRUE
        request.session[ACTIVE_TAG] = request.GET.get(TAGS)
        if todos is not None:
            todos = todos.filter(tags__name__in=[request.GET.get(TAGS)])
        if notes is not None:
            notes = notes.filter(tags__name__in=[request.GET.get(TAGS)])
        if bookmarks is not None:
            bookmarks = bookmarks.filter(
                tags__name__in=[request.GET.get(TAGS)])

    for item in [todos, notes, bookmarks]:
        if item is not None:
            queryset.append(item)

    all_items = (QuerySetSequence(
        *queryset).order_by("-date_created" if request.session.get(
            SORT_BY_CREATION) == TRUE else "date_created").filter(
                Q(name__contains=request.session.get(SEARCH))
                | Q(description__contains=request.session.get(SEARCH))))

    paginator = Paginator(all_items, 9)

    site = "index.html" if request.session.get(
        TOGGLE_VIEWTYPE) == FALSE else "index-table.html"
    return render(
        request,
        site,
        context={
            "page_obj": paginator.get_page(request.GET.get("page")),
            "tag_quantities": tag_quantities,
            "active_tag": request.session[ACTIVE_TAG],
        },
    )