Возвращает QuerySet содержащий выборку товаров
    :param slug: символьный код категории каталога, если не задан выбираются товары в не зависимости от категории
    :return:
557074
def get_all(slug=None):
    
    if slug is None:
        q = Product.objects.published()
    else:
        q = Product.objects.published().filter(sections__slug=slug)

    if getattr(settings, 'MIDNIGHT_CATALOG_PREFETCH_PARAMS', False):
        q = q.prefetch_related(Prefetch("paramvalue_set", queryset=ParamValue.objects.published().order_by('sort').prefetch_related("param")))

    q = q.prefetch_related('sections').order_by('sort', '-id')

    return q.all()
1071558
def _slugify_title(self):
        
        # Restrict slugs to their maximum number of chars, but don't split mid-word
        self.slug = slugify(self.title)
        while len(self.slug) > 255:
            self.slug = '-'.join(self.slug.split('-')[:-1])

        # Is the same slug as another entry?
        if Entry.objects.filter(slug=self.slug).exclude(id=self.id).exists():
            # Append time to differentiate.
            self.slug = self._insert_timestamp(self.slug)
162861
def get_queryset(self):
        ''''''
        strain = get_object_or_404(Strain, Strain_slug=self.kwargs['strain_slug'])
        animals = Animal.objects.filter(Strain=strain)
        return Measurement.objects.filter(animal=animals)
994196
def get_object(self):
        

        if not self.force_add and self.kwargs.get(self.slug_url_kwarg, None):
            return super(FormView, self).get_object()
        else:
            self.queryset = self.get_queryset()

        return None
906043
public function slugs()
    {
        $slugs = collect();

        $this->all()->each(function ($item) use ($slugs)
        {
            $slugs->push($item['slug']);
        });

        return $slugs;
    }
1061505
def generate_slug(self, model_instance):
        """"""
        queryset = model_instance.__class__._default_manager.all()

        # Only count slugs that match current length to prevent issues
        # when pre-existing slugs are a different length.
        lookup = {'%s__regex' % self.attname: r'^.{%s}$' % self.length}
        if queryset.filter(**lookup).count() >= len(self.chars)**self.length:
            raise FieldError("No available slugs remaining.")

        slug = get_random_string(self.length, self.chars)

        # Exclude the current model instance from the queryset used in
        # finding next valid slug.
        if model_instance.pk:
            queryset = queryset.exclude(pk=model_instance.pk)

        # Form a kwarg dict used to impliment any unique_together
        # contraints.
        kwargs = {}
        for params in model_instance._meta.unique_together:
            if self.attname in params:
                for param in params:
                    kwargs[param] = getattr(model_instance, param, None)
        kwargs[self.attname] = slug

        while queryset.filter(**kwargs):
            slug = get_random_string(self.length, self.chars)
            kwargs[self.attname] = slug

        return slug
423772
def lookup_object(model, object_id, slug, slug_field):
    
    lookup_kwargs = {}
    if object_id:
        lookup_kwargs['%s__exact' % model._meta.pk.name] = object_id
    elif slug and slug_field:
        lookup_kwargs['%s__exact' % slug_field] = slug
    else:
        raise GenericViewError(
            "Generic view must be called with either an object_id or a"
            " slug/slug_field.")
    try:
        return model.objects.get(**lookup_kwargs)
    except ObjectDoesNotExist:
        raise Http404("No %s found for %s"
                      % (model._meta.verbose_name, lookup_kwargs))
970013
def generate_slug(obj, text, tail_number=0):
    from panya.models import ModelBase
    
    # use django slugify filter to slugify
    slug = slugify(text)
    
    existing_slugs = [item.slug for item in ModelBase.objects.filter(slug__regex=r'^%s(-\d+)?' % slug).exclude(id=obj.id)]
    
    tail_number = 0
    new_slug = slug
    while new_slug in existing_slugs:
        new_slug = slugify("%s-%s" % (slug, tail_number))
        tail_number += 1
    
    return new_slug
772679
public function findOneBySlug($slug)
    {
        return $this->_em->createQueryBuilder()
            ->select('p, t, c, co')
            ->from('VeonikBlogBundle:AbstractPost', 'p')
            ->leftJoin('p.tags', 't')
            ->leftJoin('p.categories', 'c')
            ->leftJoin('p.comments', 'co')
            ->where('p.slug = :slug')
            ->andWhere('p.active = true')
            ->setParameter('slug', $slug)
            ->getQuery()
            ->getOneOrNullResult();
    }
193628
public function slugs()
    {
        $slugs = collect();

        $this->all()->each(function ($item, $key) use ($slugs) {
            $slugs->push(strtolower($item['slug']));
        });

        return $slugs;
    }
315884
public function retrieveActiveBySlug($slug)
    {
        $query = $this->createQueryBuilder('c')
            ->where('c.isActive = :isActive')
            ->andWhere('c.slug = :slug')
            ->orderBy('c.rank', 'ASC')
            ->setMaxResults(1)
            ->getQuery();

        $query->setParameter('isActive', true);
        $query->setParameter('slug', $slug);

        return $query->getOneOrNullResult();
    }
1261047
def clean_slug(self):
        
        self.instance._old_slug = self.instance.slug
        new_slug = self.cleaned_data['slug']
        if not isinstance(self.instance, Link) and new_slug != "/":
            new_slug = clean_slashes(self.cleaned_data['slug'])
        return new_slug
1312186
public function getSimilarSlugs($slug)
    {
        return $this->getSimilarSlugsBuilder($slug)
            ->select('o.slug')
            ->addSelect('o.objectClass object_class')
            ->addSelect('o.objectId object_id')
            ->getQuery()
            ->getScalarResult();
    }
1258112
public function find()
    {
        if ($this->owner->isNewRecord === false && SeoSlug::getDb()->getSchema()->getTableSchema(SeoSlug::tableName(), true) !== null) {
            //Сначала попробуем найти запись в кеше
            $this->_slugModel = $this->_cache->get($this->owner);
            if (is_null($this->_slugModel)) {
                $this->_slugModel = SeoSlug::find()
                    ->where([
                        'AND',
                        ['=', 'model', $this->owner->className()],
                        ['=', 'model_id', $this->owner->getPrimaryKey()],
                    ])
                    ->orderBy(['id' => SORT_DESC])
                    ->one();
                //Если запись найдена положим найденную запись в кеш
                if ($this->_slugModel) {
                    $this->_cache->set($this->owner, $this->_slugModel);
                }
            }
            //Если запись найдена и указано поле в родительской модели то присвоем ему значение этого алиаса
            if ($this->_slugModel && $this->slugAttribute) {
                $this->owner->{$this->slugAttribute} = $this->_slugModel->slug;
            }
        }
    }
365324
def categories(self, *category_slugs):
        
        categories_field = getattr(self.model, 'categories', None)
        if categories_field is None:
            raise AttributeError("The {0} does not include CategoriesEntryMixin".format(self.model.__name__))

        if issubclass(categories_field.rel.model, TranslatableModel):
            # Needs a different field, assume slug is translated (e.g django-categories-i18n)
            filters = {
                'categories__translations__slug__in': category_slugs,
            }

            # TODO: should the current language also be used as filter somehow?
            languages = self._get_active_rel_languages()
            if languages:
                if len(languages) == 1:
                    filters['categories__translations__language_code'] = languages[0]
                else:
                    filters['categories__translations__language_code__in'] = languages

            return self.filter(**filters).distinct()
        else:
            return self.filter(categories__slug=category_slugs)
826857
public function actionSingle( $slug ) {

		$model = $this->formService->getBySlugType( $slug, CoreGlobal::TYPE_FORM );

		if( isset( $model ) ) {

			// Find Template
			$content	= $model->modelContent;
			$template	= $content->template;

			// Fields
			$formFields	= $model->getFieldsMap();

	 		$form	= new GenericForm( [ 'fields' => $formFields ] );
			$user	= Yii::$app->user->getIdentity();

			$form->captchaAction = '/cms/form/captcha';

			$this->view->params[ 'model' ] = $model;

			// Form need a valid user
			if( !$model->isVisibilityPublic() ) {

				// Form need it's owner
				if( $model->isVisibilityPrivate() && !$model->isOwner( $user ) ) {

					// Error- Not allowed
					throw new UnauthorizedHttpException( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_NOT_ALLOWED ) );
				}

				// Form need logged in user
				if( $model->isVisibilityProtected() && empty( $user ) ) {

					// Remember URL for Login
					Url::remember( Url::canonical(), CoreGlobal::REDIRECT_LOGIN );

					// Error- Not allowed
					return $this->redirect( [ '/login' ] );
				}
			}

			if( $model->captcha ) {

				$form->setScenario( 'captcha' );
			}

			if( $form->load( Yii::$app->request->post(), 'GenericForm' ) && $form->validate() ) {

				// Save Model
				if( $this->formService->processForm( $model, $form ) ) {

					// Trigger User Mail
					if( $model->userMail ) {

						Yii::$app->formsMailer->sendUserMail( $model, $form );
					}

					// Trigger Admin Mail
					if( $model->adminMail ) {

						Yii::$app->formsMailer->sendAdminMail( $model, $form );
					}

					// Set success message
					if( isset( $model->success ) ) {

						Yii::$app->session->setFlash( 'message', $model->success );
					}

					// Refresh the Page
		        	return $this->refresh();
				}
			}

			// Fallback to default template
			if( empty( $template ) ) {

				$template = $this->templateService->getGlobalBySlugType( FormsGlobal::TEMPLATE_FORM, CoreGlobal::TYPE_FORM );
			}

			if( isset( $template ) ) {

				return Yii::$app->templateManager->renderViewPublic( $template, [
		        	'model' => $model,
					'form' => $form,
					'content' => $content,
					'banner' => $content->banner
		        ], [ 'page' => true ] );
			}

	        return $this->render( CoreGlobalWeb::PAGE_INDEX, [
				'model' => $model,
				'form' => $form
	        ]);
		}

		// Model not found
		throw new NotFoundHttpException( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_NOT_FOUND ) );
	}
1365387
def populate_slug(instance, field):
    '''
    
    '''
    value = getattr(instance, field.db_field)

    try:
        previous = instance.__class__.objects.get(id=instance.id)
    except Exception:
        previous = None

    # Field value has changed
    changed = field.db_field in instance._get_changed_fields()
    # Field initial value has been manually set
    manual = not previous and value or changed

    if not manual and field.populate_from:
        # value to slugify is extracted from populate_from parameter
        value = getattr(instance, field.populate_from)
        if previous and value == getattr(previous, field.populate_from):
            return value

    if previous and getattr(previous, field.db_field) == value:
        # value is unchanged from DB
        return value

    if previous and not changed and not field.update:
        # Field is not manually set and slug should not update on change
        return value

    slug = field.slugify(value)

    # This can happen when serializing an object which does not contain
    # the properties used to generate the slug. Typically, when such
    # an object is passed to one of the Celery workers (see issue #20).
    if slug is None:
        return

    old_slug = getattr(previous, field.db_field, None)

    if slug == old_slug:
        return slug

    # Ensure uniqueness
    if field.unique:
        base_slug = slug
        index = 1
        qs = instance.__class__.objects
        if previous:
            qs = qs(id__ne=previous.id)

        def exists(s):
            return qs(
                class_check=False, **{field.db_field: s}
            ).limit(1).count(True) > 0

        while exists(slug):
            slug = '{0}-{1}'.format(base_slug, index)
            index += 1

    # Track old slugs for this class
    if field.follow and old_slug != slug:
        ns = instance.__class__.__name__
        # Destroy redirections from this new slug
        SlugFollow.objects(namespace=ns, old_slug=slug).delete()

        if old_slug:
            # Create a redirect for previous slug
            slug_follower, created = SlugFollow.objects.get_or_create(
                namespace=ns,
                old_slug=old_slug,
                auto_save=False,
            )
            slug_follower.new_slug = slug
            slug_follower.save()

            # Maintain previous redirects
            SlugFollow.objects(namespace=ns, new_slug=old_slug).update(new_slug=slug)

    setattr(instance, field.db_field, slug)
    return slug