Monday, May 22, 2017

Re: Building correct queryset

Hello, Дмитрий,
you can try this one, but w/o further optimizations it may be a very slow query.

qs = Product.objects.filter(
   
#Where score is greater or equal
   
#to the 4th max score from its group
    score__gte
=Subquery(
       
(Product.objects
           
.filter(brand=OuterRef('brand'))
           
.values('score')
           
.order_by('-score')[3:4]
       
)
   
)
).order_by('-score')




 

On Friday, May 19, 2017 at 12:32:49 PM UTC+3, Горобец Дмитрий wrote:
Hello. I have these two models. I have to show 4 or less products on a page for each brand ordered by score. Please, help construct correct queryset.


class Brand(models.Model):
title = models.CharField(
verbose_name='Название бренда',
max_length=64,
unique=True,
db_index=True,
error_messages={
'unique': 'Бренд с таким именем уже существует.'
}
)

slug = AutoSlugField(
verbose_name='Адрес страницы бренда',
populate_from='title',
editable=True,
unique=True,
slugify=custom_slugify,
db_index=True
)

owner = models.OneToOneField(
to=settings.AUTH_USER_MODEL,
verbose_name='Владелец',
on_delete=models.PROTECT,
)

    score = models.DecimalField(
verbose_name='Рейтинг бренда',
blank=True,
null=True,
max_digits=19,
decimal_places=18,
)


class Product(models.Model):
title = models.CharField(
verbose_name='Название изделия',
max_length=255,
db_index=True,
)

slug = AutoSlugField(
verbose_name='Адрес страницы изделия',
populate_from='title',
editable=False,
unique_with='brand',
slugify=custom_slugify,
db_index=True,
)

brand = models.ForeignKey(
to=Brand,
verbose_name='Бренд',
related_name='products',
on_delete=models.CASCADE,
)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/16251879-81fd-4f25-83b7-5f6c920e3f8a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment