Thursday, 1 January 2015

Python & Django tips

Some code snippets that I've found useful. (Mostly from stackoverflow.com, sorry for not pointing to the actual answers, my bookmarks are a mess)

Ordering by custom column in Django admin:


You have to annotate your QuerySet, add a method for your custom column and enable ordering on it.

Here we want to display how many books each Publisher has. And display the Publisher's name and the book count in the admin interface.

We override get_queryset and annotate the QuerySet.

class PublisherAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        return Publisher.objects.annotate(book_count=Count('book'))

    # Return the annotated column's name
    def total_books(self, publisher_object):
        return publisher_object.book_count
    # Enable ordering
    total_books.admin_order_field = 'book_count'

    list_display = ('name', 'total_books')

Serializing datetime (and possibly other) objects when passed to json.dumps


def _unix_time(dt):
    epoch = datetime.date.fromtimestamp(0)
    delta = dt - epoch
    return delta.total_seconds()

def serialize_datetime(obj):
    if hasattr(obj, 'isoformat'):
        return obj.isoformat()
        # Or if you want the date in another format
        # return obj.strftime('%d-%m-%Y')
        
        # To get ms since epoch
        # return _unix_time(obj)
    return None

j = json.dumps(list_of_objects_with_datetime, default=serialize_datetime)


Ordering by multiple fields, aggregating and ordering QuerySet.


This seems difficult to achieve at first, but it couldn't be easier.

MyModel.objects.values('A', 'B') \
    .annotate(count=Sum('C')) \
    .order_by('A')

In the above example, you group by columns A and B. Then you can Count or Sum another column (the aggregation), and finally we order by one of the columns we grouped by (A or B) or the annotated column (count).

No comments:

Post a Comment