S
S
Sergey Nizhny Novgorod2016-12-26 00:22:11
Django
Sergey Nizhny Novgorod, 2016-12-26 00:22:11

How to efficiently select the next largest element in Django?

Hello.
Situation
There is an element model where there is a name and number of likes

Element

title = models.CharField()
number_of_likes = models.IntegerField()

The number of likes for each item increases by an unknown number after user actions.
===
Problem
1) We know one element,
2) We need to display one more element, the number of likes of which follows the element from point 1 (if the elements were sorted in ascending order by the number of likes).
===
Given that the number of likes is constantly changing, the only solution so far seems to be sorting the elements by the number of likes each time the information is displayed. But is there a smarter way to do this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman Kitaev, 2016-12-26
@Terras

Element.objects.filter(number_of_likes__gt=el.number_of_likes).order_by('number_of_likes').first()

R
Rsa97, 2017-05-25
@Evgenij_nechujveter

Because in each case you are comparing $day with the result of the formula calculation.
Your entry is equivalent to the following:

if ($day == ($day == 1 && $day <= 5)) { }
elseif ($day == ($day === 6 && $day === 7)) {}
elseif ($day == ($day == 0 && $day > 7)) {}

This is not to mention the curvature of the conditions themselves.
($day == 1 && $day <= 5)executed only if $day == 1.
($day === 6 && $day === 7)never executed.
($day == 0 && $day > 7)also never executed.
If you want to use exactly switch, then like this:
switch ($day) {
  case 1:
  case 2:
  case 3:
  case 4:
  case 5:
    echo ... ;
    break;
  case 6:
  case 7:
    echo ... ;
    break;
  default:
    echo ... ;
    break;
}

A
Artem, 2017-05-25
@devspec

$day === 6 || $day === 7
as well as
$day <= 0 || $day > 7

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question