How to output Django queryset as JSON?

You can use JsonResponse with values. Simple example: from django.http import JsonResponse def some_view(request): data = list(SomeModel.objects.values()) # wrap in list(), because QuerySet is not JSON serializable return JsonResponse(data, safe=False) # or JsonResponse({‘data’: data}) Or another approach with Django’s built-in serializers: from django.core import serializers from django.http import HttpResponse def some_view(request): qs = SomeModel.objects.all() qs_json … Read more

Django SUM Query?

Update: The following incorporates the ISNULL aspect of the original query: from django.db.models import Sum ModelName.objects.filter(field_name__isnull=True).aggregate(Sum(‘field_name’)) # returns {‘field_name__sum’: 1000} for example You’re looking for the Sum aggregation function, which works as follows: ModelName.objects.aggregate(Sum(‘field_name’)) See: https://docs.djangoproject.com/en/dev/ref/models/querysets/#sum

Getting a count of objects in a queryset in Django

To get the number of votes for a specific item, you would use: vote_count = Item.objects.filter(votes__contest=contestA).count() If you wanted a break down of the distribution of votes in a particular contest, I would do something like the following: contest = Contest.objects.get(pk=contest_id) votes = contest.votes_set.select_related() vote_counts = {} for vote in votes: if not vote_counts.has_key(vote.item.id): vote_counts[vote.item.id] … Read more

Get the latest record with filter in Django

See the docs from django: https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest You need to specify a field in latest(). eg. obj= Model.objects.filter(testfield=12).latest(‘testfield’) Or if your model’s Meta specifies get_latest_by, you can leave off the field_name argument to earliest() or latest(). Django will use the field specified in get_latest_by by default.

many-to-many in list display django

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

Select DISTINCT individual columns in django?

One way to get the list of distinct column names from the database is to use distinct() in conjunction with values(). In your case you can do the following to get the names of distinct categories: q = ProductOrder.objects.values(‘Category’).distinct() print q.query # See for yourself. # The query would look something like # SELECT DISTINCT … Read more