Why do I get different results if I use first () vs last () in a QuerySet with a length of 1

when writing a test test for a method, I found that I get different results if I use my_queryset.first (). my_annotated_value than when I use my_queryset.last (). my_annotated_value, although my_queryset.count () returns 1.

Here is the relevant code snippet:

class ShopManager(models.Manager):

def get_best_matches(self, customer):

    shops = super(ShopManager, self).get_queryset().filter(employees__matches__customer=customer).annotate(max_match_percentage=Coalesce(Max('employees__matches__match_value'), 0)).order_by('-max_match_percentage')

    for shop in shops:
        shop.max_match_percentage = float(shop.max_match_percentage) * 100.0

    return shops

In the shell, I run:

shops = Shop.objects.get_best_matches(customer=Customer_A)
shops.count() # returns 1

shops.first().max_match_percentage # returns 73.9843
shops.last().max_match_percentage # returns Decimal('0.739843')

I have a different django applications for shops, matches, employeesand customers.

I searched the clock and checked the implementation for first () and last () in django docs. I could not find anything that explains this behavior.

Why different meanings, what exactly is happening? Am I doing something wrong or is this a mistake?

+4
1

get_best_matches shop.max_match_percentage .

first(), Django .

last(), Django . . shop.max_match_percentage , .

, , , . (, filter(), order_by() last()), .

100 , :

shops = super(ShopManager, self).get_queryset().filter(employees__matches__customer=customer).annotate(max_match_percentage=Coalesce(Max('employees__matches__match_value'), 0)*100).order_by('-max_match_percentage')

float , Cast.

+5

Source: https://habr.com/ru/post/1678431/


All Articles