diff --git a/polymorphic/query.py b/polymorphic/query.py index 60ea24a..3ecaea5 100644 --- a/polymorphic/query.py +++ b/polymorphic/query.py @@ -64,6 +64,16 @@ class PolymorphicQuerySet(QuerySet): new.polymorphic_disabled = self.polymorphic_disabled return new + if django.VERSION >= (1,7): + def as_manager(cls): + # Make sure the Django 1.7 way of creating managers works. + from .manager import PolymorphicManager + manager = PolymorphicManager.from_queryset(cls)() + manager._built_with_as_manager = True + return manager + as_manager.queryset_only = True + as_manager = classmethod(as_manager) + def non_polymorphic(self, *args, **kwargs): """switch off polymorphic behaviour for this query. When the queryset is evaluated, only objects of the type of the diff --git a/polymorphic/tests.py b/polymorphic/tests.py index b14503e..13cb3ba 100644 --- a/polymorphic/tests.py +++ b/polymorphic/tests.py @@ -6,6 +6,7 @@ from __future__ import print_function import uuid import re import django +from unittest import skipIf from django.db.models.query import QuerySet from django.test import TestCase @@ -113,6 +114,11 @@ class ModelWithMyManager(ShowFieldTypeAndContent, Model2A): objects = MyManager() field4 = models.CharField(max_length=10) +if django.VERSION >= (1,7): + class ModelWithMyManager2(ShowFieldTypeAndContent, Model2A): + objects = MyManagerQuerySet.as_manager() + field4 = models.CharField(max_length=10) + class MROBase1(ShowFieldType, PolymorphicModel): objects = MyManager() field1 = models.CharField(max_length=10) # needed as MyManager uses it @@ -684,6 +690,21 @@ class PolymorphicTests(TestCase): self.assertIs(type(ModelWithMyManager._default_manager), MyManager) self.assertIs(type(ModelWithMyManager.base_objects), models.Manager) + @skipIf(django.VERSION < (1,7), "This test needs Django 1.7+") + def test_user_defined_queryset_as_manager(self): + self.create_model2abcd() + ModelWithMyManager2.objects.create(field1='D1a', field4='D4a') + ModelWithMyManager2.objects.create(field1='D1b', field4='D4b') + + objects = ModelWithMyManager2.objects.all() + self.assertEqual(repr(objects[0]), '') + self.assertEqual(repr(objects[1]), '') + self.assertEqual(len(objects), 2) + + self.assertEqual(type(ModelWithMyManager2.objects).__name__, 'PolymorphicManagerFromMyManagerQuerySet') + self.assertEqual(type(ModelWithMyManager2._default_manager).__name__, 'PolymorphicManagerFromMyManagerQuerySet') + self.assertIs(type(ModelWithMyManager2.base_objects), models.Manager) + def test_manager_inheritance(self): # by choice of MRO, should be MyManager from MROBase1. @@ -829,6 +850,7 @@ class PolymorphicTests(TestCase): t.delete() + class RegressionTests(TestCase): def test_for_query_result_incomplete_with_inheritance(self):