Django: Band?

I am looking for something like the following:

previous_invoices = Invoice.objects.filter(is_open=False)
                                   .order_by('-created')
                                   .group_by('user')

but group_by()does not exist ...

This will allow you to find the last closed invoice for each user.

This aggregation API seems to allow you to do things like calculations and amounts, but I don't need an account or amount or nothing, I really want account objects!

+3
source share
2 answers

Option 1:

Despite the fact that Django does not exist group_by(), you can try and do it when you receive the last closed account for each user, using the latest()filter for the user:

previous_invoices = Invoice.objects.filter(user=my_user, is_open=False)
                                   .latest('created') 

Django latest() , :

previous_invoices = Invoice.objects.filter(user=my_user, is_open=False)
                                   .order_by('-created')[0]

2:

group_by, , : Django GROUP BY.

  • .values_list() flat=True, ( , ). .distinct() , :

    value_list = MyModel.objects.values_list(
        'interesting_field', flat=True
    ).distinct()
    
  • value_list :

    group_by_value = {}
    for value in value_list:
        group_by_value[value] = MyModel.objects.filter(interesting_field=value)
    

group_by_value interesting_field , MyModel interesting_field=a value from value_list.


:

django-group-by, , group_by() Django, .

+1

2007, , , 1.1 group_by` . , , . :

Django "GROUP BY" - , ORM. , , API ORM SQL-. , "GROUP BY", SQL ( ).

. extra, , . .

+2

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


All Articles