Limiting Memory Use in a *Large* Django QuerySet

What about using django core’s Paginator and Page objects documented here: https://docs.djangoproject.com/en/dev/topics/pagination/ Something like this: from django.core.paginator import Paginator from djangoapp.models import SomeModel paginator = Paginator(SomeModel.objects.all(), 1000) # chunks of 1000 for page_idx in range(1, paginator.num_pages): for row in paginator.page(page_idx).object_list: # here you can do what you want with the row print “done processing page … Read more

JSON Serializing Django Models with simplejson

I would go with extending simplejson. Basically, you want to plug in django’s serialization when the JSON encoder encounters a QuerySet. You could use something like: from json import dumps, loads, JSONEncoder from django.core.serializers import serialize from django.db.models.query import QuerySet from django.utils.functional import curry class DjangoJSONEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, QuerySet): # `default` must … Read more

In Django, can you add a method to querysets?

As of django 1.7, the ability to use a query set as a manager was added: class PersonQuerySet(models.QuerySet): def authors(self): return self.filter(role=”A”) def editors(self): return self.filter(role=”E”) class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) role = models.CharField(max_length=1, choices=((‘A’, _(‘Author’)), (‘E’, _(‘Editor’)))) people = PersonQuerySet.as_manager() Resulting the following: Person.people.authors(last_name=”Dahl”) In addition, the ability to add custom … Read more

How to seed Django project ? – insert a bunch of data into the project for initialization

Similar to Rails, we also have option to seed the database. It is done using management commands. In one of your apps, use the following folder structure <project>/<app>/management/commands/seed.py this makes python manage.py seed available as a management command. I personally follow the following structure. # <project>/<app>/management/commands/seed.py from django.core.management.base import BaseCommand import random # python manage.py … Read more

Django equivalent of COUNT with GROUP BY

If you are using Django 1.1 beta (trunk): Player.objects.values(‘player_type’).order_by().annotate(Count(‘player_type’)) values(‘player_type’) – for inclusion only player_type field into GROUP BY clause. order_by() – for exclusion possible default ordering that can cause not needed fields inclusion in SELECT and GROUP BY.

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)