Desiigner
Desiigner

Reputation: 2316

Getting 3 previous items in django queryset

I know there are similar questions but they don't answer mine. Say I have a sequence of letters:

A B C D E F G

I want to pass only 3 letters to my template based on a specific letter, and those 3 letters must be previous ones. For example, If this letter is D then it must be:

A B C

If it's E then it's:

B C D

and etc.

I understand the way slicing works but all I can do is to get the first 3 letters of my query set:

context['words'] = WordsAndLetters.objects.exclude(letter=letter).order_by('letter')[:3]

I'm also excluding my specific letter to just show 3 previous. How can I get to the right result?

Upvotes: 0

Views: 46

Answers (1)

Viktor Petrov
Viktor Petrov

Reputation: 444

Try this:

    specific_letter = WordsAndLetters.objects.get(letter=your_specific_letter) # your specific letter;
    all_letters = list(WordsAndLetters.objects.all().order_by('letter'))  # all letters in a sorted list;
    index = all_letters.index(specific_letter)  # find out the index of your specific letter;
    context['words'] = all_letters[index-4:index-1] # slice three letters before your specific letter index, e.g. if your index is 6 the slice would be [2:5];

Of course, this doesn't account for the case when you're slicing until A, B or C, since they don't have three letters preceeding them.

Upvotes: 1

Related Questions