How to show a many-to-many field with “list_display” in Django Admin?

You may not be able to do it directly. From the documentation of list_display ManyToManyField fields aren’t supported, because that would entail executing a separate SQL statement for each row in the table. If you want to do this nonetheless, give your model a custom method, and add that method’s name to list_display. (See below … Read more

aggregate() vs annotate() in Django

I would focus on the example queries rather than your quote from the documentation. Aggregate calculates values for the entire queryset. Annotate calculates summary values for each item in the queryset. Aggregation >>> Book.objects.aggregate(average_price=Avg(‘price’)) {‘average_price’: 34.35} Returns a dictionary containing the average price of all books in the queryset. Annotation >>> q = Book.objects.annotate(num_authors=Count(‘authors’)) >>> … Read more

How to combine multiple QuerySets in Django?

Concatenating the querysets into a list is the simplest approach. If the database will be hit for all querysets anyway (e.g. because the result needs to be sorted), this won’t add further cost. from itertools import chain result_list = list(chain(page_list, article_list, post_list)) Using itertools.chain is faster than looping each list and appending elements one by … Read more

How to use Query Strings for filtering Querysets in Django?

Here is the code: class PassengerList(generics.ListCreateAPIView): model = Passenger serializer_class = PassengerSerializer # Show all of the PASSENGERS in particular WORKSPACE # or all of the PASSENGERS in particular AIRLINE def get_queryset(self): queryset = Passenger.objects.all() workspace = self.request.query_params.get(‘workspace’) airline = self.request.query_params.get(‘airline’) if workspace: queryset = queryset.filter(workspace_id=workspace) elif airline: queryset = queryset.filter(workspace__airline_id=airline) return queryset