Exemple #1
0
class ShrewdManager(BaseManager.from_queryset(ShrewdQuerySet)):
    '''
    Shrewd manager for models.

    Manages only objects of the model which are __not in__ the recycle bin.
    '''
    pass
Exemple #2
0
class NewBaseManager(BaseManager.from_queryset(QuerySetEx)):
    def get(self, *args, **kwargs):
        data = None
        selfmodel = self.model
        # print selfmodel
        memcache_obj = selfmodel.memcached()
        query_key = memcache_obj.cache_query_key(**kwargs)
        # print querykey,"querycache===="
        if query_key:
            data_key = memcache_obj.get(query_key)
            if data_key:
                data = memcache_obj.get(data_key)
                if not data:
                    data = super(NewBaseManager, self).get(*args, **kwargs)
                    data.set_cache_db_key()
            else:
                data = super(NewBaseManager, self).get(*args, **kwargs)
                data_key = data.set_cache_db_key()
                memcache_obj.set(query_key, data_key, 60 * 3)
        else:
            data = super(NewBaseManager, self).get(*args, **kwargs)
        return data

    def get_queryset(self):

        return super(NewBaseManager, self).get_queryset()
Exemple #3
0
class NaiveManager(BaseManager.from_queryset(NaiveQuerySet)):
    '''
    Naive manager for models.

    Manages __all__ the objects of the model in the database.
    '''
    pass
Exemple #4
0
class Person(models.Model):
    GENDER_MALE = "m"
    GENDER_FEMALE = "f"
    GENDER_CHOICES = (
        (GENDER_MALE, "Male"),
        (GENDER_FEMALE, "Female"),
    )

    id = models.CharField(primary_key=True, max_length=10)
    subid = models.IntegerField()
    name = models.CharField(max_length=80, blank=True, null=True)
    country = models.ForeignKey(
        Country,
        max_length=50,
        null=True,
        on_delete=models.DO_NOTHING,
    )
    gender = models.CharField(max_length=1,
                              choices=GENDER_CHOICES,
                              blank=True,
                              null=True)

    objects = BaseManager.from_queryset(PersonQuerySet)()

    class Meta:
        unique_together = (("id", "subid"), )
        base_manager_name = "objects"
Exemple #5
0
class RecycleBinManager(BaseManager.from_queryset(RecycleBinQuerySet)):
    '''
    Recycle bin manager for models.

    Manages only objects of the model which are __in__ the recycle bin.
    '''
    pass
class TranslationManager(BaseManager.from_queryset(TranslationQuerySet)):
    def get_translation_model(self):
        return self.model.get_translation_model()

    def get_translation_model_reverse_query_name(self):
        return self.model.get_translation_model_reverse_query_name()

    def get_translation_model_field_names(self,
                                          reverse=False,
                                          m2m=False,
                                          own=True):
        return self.model.get_translation_model_field_names(reverse, m2m, own)

    def get_annotate_params(self):
        reverse_name = self.get_translation_model_reverse_query_name()
        fields = self.get_translation_model_field_names()
        annotate_params = {}
        for f in fields:
            annotate_params[f] = models.F('{}__{}'.format(reverse_name, f))
        return annotate_params

    def get_queryset(self):
        q = super(TranslationManager, self).get_queryset()
        q = q.annotate(**self.get_annotate_params())
        return q.all()
Exemple #7
0
class LetterManager(BaseManager.from_queryset(LetterQuerySet)):
    def get_queryset(self):
        return (
            super()
            .get_queryset()
            .filter(is_spam__in=[Letter.SPAM.unknown, Letter.SPAM.non_spam])
        )
Exemple #8
0
class ModelManager(BaseManager.from_queryset(QuerySet)):
    def __init__(self):
        super().__init__()
        self.instance = None
        # False 이면 self 가 source, True 이면 self 가 target (is_source 는 self 가 아니라 subfield 의 속성)
        self.reverse = None
        self.rel_type = None
        self.multiplicity = None
        self.target_field_name = None  # for avoid pycharm warning
        self.subfield = None
        self.related_subfield = None

    def process_queryset(self, qs):
        types = self.model.types
        if types:
            qs = qs.filter(type__in=types)
        return qs

    def get_queryset(self):
        qs = super().get_queryset().filter(status__in=(Status.NORMAL, Status.WORKING))
        return self.process_queryset(qs)

    def get_deleted(self, *args, **kwargs):
        kwargs = self.model.resolve_subfield_filters(**kwargs)
        assert kwargs["id"], "get_deleted() 호출 시에는 id 값을 넘겨야 합니다."
        qs = DjangoQuerySet(self.model)
        qs = qs.filter(status=Status.DELETED)
        qs = self.process_queryset(qs)
        instance = qs.get(*args, **kwargs)
        if instance.status != Status.DELETED:
            raise instance.__class__.DoesNotExist
        instance._old_status = Status.DELETED
        return instance

    def create(self, **kwargs):
        model = self.model
        kwargs = model.resolve_subfield_filters(**kwargs)
        obj = model(**kwargs)
        self._for_write = True
        assert obj.status in (Status.CREATING, Status.NEW), "인스턴스 생성이 최종 완료되기 전에 다른 곳에서 save() 가 먼저 호출되었습니다."
        obj.save()
        return obj

    def get_or_create(self, is_update_if_exist=False, **kwargs):
        model = self.model
        kwargs = model.resolve_subfield_filters(**kwargs)
        keys = {}
        for key in model.UNIQUE_KEY_SUBFIELD_NAMES + model.PSEUDO_KEY_SUBFIELD_NAMES:
            if key in kwargs:
                keys[key] = kwargs.pop(key)
        try:
            instance, is_create = self.get(**keys), False
            if is_update_if_exist:
                instance.patch(**kwargs)
                instance.save()
        except model.DoesNotExist:
            # uname 이 DerivedUnameSubfield 인 경우 kwargs 에 의해 계산되기 때문에 keys 보다 kwargs 가 먼저 전달되어야 한다.
            instance, is_create = self.create(**kwargs, **keys), True
        return instance, is_create
Exemple #9
0
class ConversationMessageManager(
        BaseManager.from_queryset(ConversationMessageQuerySet)):
    def create(self, **kwargs):
        obj = super().create(**kwargs)
        # clear cached value
        if obj.thread and hasattr(obj.thread, '_replies_count'):
            del obj.thread._replies_count
        return obj
Exemple #10
0
    class base_manager_class(BaseManager.from_queryset(NodbQuerySet), Manager):
        """in DRF 3, rest_framework.relations.RelatedField#get_queryset checks:

        >>> isinstance(queryset, Manager)

        This is unfortunate, but we have to inherent from `Manager`, too!
        """
        pass
Exemple #11
0
class BasicContentManager(QueryManager,
                          BaseManager.from_queryset(BasicContentQuerySet)):
    """
    初始化时支持传入过滤参数
    https://django-model-utils.readthedocs.io/en/stable/managers.html#querymanager
    """
    def get_queryset(self):
        return super().get_queryset().filter(is_removed=False)
Exemple #12
0
class PandasDataFrameManager(BaseManager.from_queryset(DataFrame)):

    _queryset_class = PandasQuerySet

    def get_queryset(self):
        kwargs = {'model': self.model, 'using': self._db}
        if hasattr(self, '_hints'):
            kwargs['hints'] = self._hints
        return self._queryset_class(**kwargs)
Exemple #13
0
class CustomManager(BaseManager.from_queryset(CustomQuerySet)):
    def get_queryset(self):
        """
        Return a new QuerySet object. Subclasses can override this method to
        customize the behavior of the Manager.
        """
        return self._queryset_class(model=self.model,
                                    using=self._db,
                                    hints=self._hints,
                                    query=CustomQuery(self.model))
Exemple #14
0
class DataMartManager(BaseManager.from_queryset(DataMartQuerySet)):

    def truncate(self, reset=True):
        if reset:
            restart = 'RESTART IDENTITY'
        else:
            restart = ''
        with connections['default'].cursor() as cursor:
            cursor.execute('TRUNCATE TABLE "{0}" {1} CASCADE;'.format(self.model._meta.db_table,
                                                                      restart))
Exemple #15
0
class DataStore(models.Model):
    key = models.CharField(
        max_length=255,
        primary_key=True,
    )
    value = JSONField(default=dict, blank=False)

    objects = BaseManager.from_queryset(DataStoreQuerySet)()

    class Meta:
        ordering = ['key']
Exemple #16
0
class BaseModelMange(BaseManager.from_queryset(CustomQuerySet)):
    def all(self):
        return self.filter().all()

    def filter(self, *args, **kwargs):
        fields = {i.name for i in self.model._meta.fields}
        if 'is_active' in fields and not kwargs.get('is_active'):
            kwargs['is_active'] = True
        elif 'status' in fields and not kwargs.get('status'):
            kwargs['status'] = 0
        return super().filter(*args, **kwargs)
Exemple #17
0
class NotificationManager(BaseManager.from_queryset(NotificationQuerySet)):
    def create_for_pickup_collectors(self, collectors, type):
        for collector in collectors:
            pickup = collector.pickupdate
            super().create(user=collector.user,
                           type=type,
                           context={
                               'group': pickup.group.id,
                               'place': pickup.place.id,
                               'pickup': pickup.id,
                               'pickup_collector': collector.id,
                           })
Exemple #18
0
class NotificationManager(BaseManager.from_queryset(NotificationQuerySet)):
    def create_for_activity_participants(self, participants, type):
        for participant in participants:
            activity = participant.activity
            super().create(user=participant.user,
                           type=type,
                           context={
                               'group': activity.group.id,
                               'place': activity.place.id,
                               'activity': activity.id,
                               'activity_participant': participant.id,
                           })
class IndexEntryManager(BaseManager.from_queryset(SearchQuerySet)):
    def contribute_to_class(self, cls, name, **kwargs):
        super().contribute_to_class(cls, name, **kwargs)
        IndexManager.register(cls)

    @property
    def target_model(self):
        try:
            return self.model._meta.get_field(
                self.model.object_field).remote_field.model
        except FieldDoesNotExist:
            return None

    def get_or_prepare(self, obj):
        model = self.get_index_model(obj._meta.model)
        if not model:
            raise RuntimeError(
                f"Index for {obj._meta.model_name} is not configured.")
        try:
            indexed = model._meta.default_manager.get(
                **{model.object_field: obj})
            setattr(indexed, model.object_field, obj)
            return indexed
        except model.DoesNotExist:
            return model(object=obj)

    def get_index_model(self, model):
        if model == self.target_model:
            return self.model

        for subcls in self.model.__subclasses__():
            index = subcls._meta.default_manager.get_index_model(model)
            if index:
                return index
        return None

    def refresh(self, objects, break_on_failure=False):
        for obj in objects:
            try:
                self.get_or_prepare(obj).save()
            except Exception:
                logger.exception(
                    f"Exception raised when updating index for '{obj}'")
                if break_on_failure:
                    raise

    def rebuild(self):
        if self.target_model:
            return self.refresh(self.model.get_index_queryset())

        for subcls in self.model.__subclasses__():
            subcls._meta.default_manager.rebuild()
Exemple #20
0
class ConversationMessageManager(BaseManager.from_queryset(ConversationMessageQuerySet)):
    def create(self, **kwargs):
        if 'thread' not in kwargs:
            # make sure author is participant (to receive notifications)
            conversation = kwargs.get('conversation')
            author = kwargs.get('author')
            conversation.conversationparticipant_set.get_or_create(user=author)

        obj = super().create(**kwargs)
        # clear cached value
        if obj.thread and hasattr(obj.thread, '_replies_count'):
            del obj.thread._replies_count
        return obj
class TransactionManager(BaseManager.from_queryset(TransactionQuerySet)):
    """ Custom manager """

    def get_for_token(self, tidb64, token):
        transaction = None
        try:
            tid = urlsafe_base64_decode(tidb64).decode()
            transaction = Transaction.objects.get(pk=tid)
            if not default_token_generator.check_token(transaction, token):
                transaction = None
        except (TypeError, ValueError, OverflowError, ObjectDoesNotExist, ValidationError):
            pass

        return transaction
Exemple #22
0
class ExchangeRate(models.Model):
    source = models.PositiveSmallIntegerField(
        choices=currency_exchange_choices,
        help_text=_('Where the exchange data comes from'),
    )
    base_currency = models.CharField(max_length=3, db_index=True)
    rates = models.JSONField(default=dict)
    last_updated_at = models.DateTimeField(auto_now=True, db_index=True)
    objects = BaseManager.from_queryset(ExchangeRateQuerySet)()

    class Meta:
        ordering = ['base_currency', '-last_updated_at']

    def __repr__(self):
        return 'Exchange rate for {0}'.format(self.base_currency)
Exemple #23
0
class EntityManager(BaseManager.from_queryset(EavQuerySet)):
    """
    Our custom manager, overrides ``models.Manager``.
    """
    _queryset_class = EavQuerySet

    def create(self, **kwargs):
        """
        Parse eav attributes out of *kwargs*, then try to create and save
        the object, then assign and save it's eav attributes.
        """
        config_cls = getattr(self.model, '_eav_config_cls', None)

        if not config_cls or config_cls.manager_only:
            return super(EntityManager, self).create(**kwargs)

        prefix = '%s__' % config_cls.eav_attr
        new_kwargs = {}
        eav_kwargs = {}

        for key, value in kwargs.items():
            if key.startswith(prefix):
                eav_kwargs.update({key[len(prefix):]: value})
            else:
                new_kwargs.update({key: value})

        obj = self.model(**new_kwargs)
        obj_eav = getattr(obj, config_cls.eav_attr)

        for key, value in eav_kwargs.items():
            setattr(obj_eav, key, value)

        obj.save()
        return obj

    def get_or_create(self, **kwargs):
        """
        Reproduces the behavior of get_or_create, eav friendly.
        """
        try:
            return self.get(**kwargs), False
        except self.model.DoesNotExist:
            return self.create(**kwargs), True
Exemple #24
0
class SerializableManager(BaseManager.from_queryset(SerializableQuerySet)):
    def __init__(self,
                 *,
                 select_related=None,
                 prefetch_related=None,
                 default_serializer=BaseSerializer):
        super().__init__()
        self.default_serializer = default_serializer(
            select_related=select_related,
            prefetch_related=prefetch_related,
        )

    def to_serialize(self, serializer=None):
        if serializer is None:
            serializer = self.default_serializer
        return self.get_queryset().to_serialize(serializer)

    @classmethod
    def from_queryset(cls, queryset_class, class_name=None):
        if not hasattr(queryset_class, 'to_serialize'):
            queryset_class = type(
                f'SerializableQuerySet__{queryset_class.__name__}',
                (SerializableQuerySet, queryset_class), {})
        return super().from_queryset(queryset_class, class_name=class_name)
Exemple #25
0
class EntryManager(BaseManager.from_queryset(EntryQuerySet)):
    use_for_related_fields = True
Exemple #26
0
class AccountManager(BaseManager.from_queryset(AccountQuerySet)):
    use_for_related_fields = True
class PIDManager(BaseManager.from_queryset(PIDQuerySet)):
    pass
Exemple #28
0
class JobManager(BaseManager.from_queryset(JobQueryset)):
    """ Custom manager from queryset """

    pass
Exemple #29
0
class GroupManager(BaseManager.from_queryset(GroupQuerySet)):
    use_for_related_fields = True
Exemple #30
0
class TaskManager(BaseManager.from_queryset(TaskQuerySet)):
    use_for_related_fields = True
Exemple #31
0
    name = models.CharField(max_length=100)
    slug = models.SlugField()

    class Meta:
        ordering = ['name']

    def __str__(self):
        return self.name


class DoesNotExistQuerySet(QuerySet):
    def get(self, *args, **kwargs):
        raise Author.DoesNotExist


DoesNotExistBookManager = BaseManager.from_queryset(DoesNotExistQuerySet)


class Book(models.Model):
    name = models.CharField(max_length=300)
    slug = models.SlugField()
    pages = models.IntegerField()
    authors = models.ManyToManyField(Author)
    pubdate = models.DateField()

    objects = models.Manager()
    does_not_exist = DoesNotExistBookManager()

    class Meta:
        ordering = ['-pubdate']
 def get_manager(cls):
     return type('DictManager', (BaseManager.from_queryset(cls)), {})