Created
July 5, 2012 18:44
-
-
Save ei-grad/3055603 to your computer and use it in GitHub Desktop.
get_bound_objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding: utf-8 | |
def get_bound_objects(queryset, classes): | |
""" | |
Helper function to map a list of objects to corresponding classes in Django ORM. | |
It is a simple and stupid alternative to django_polymorphic. | |
Good to use with custom Paginator class. Example usage: | |
class Order(models.Model): | |
# some common fields | |
pass | |
class CashOrder(Order): | |
# some specific fields | |
pass | |
class CreditCardOrder(Order): | |
# some specific fields | |
pass | |
class PaypalOrder(Order): | |
# some specific fields | |
pass | |
class OrderPaginator(Paginator): | |
def page(self, number): | |
_page = super(OrderPaginator, self).page(number) | |
_page.object_list = get_bound_objects(_page.object_list, [CashOrder, CreditCardOrder, PaypalOrder]) | |
return _page | |
class OrdersListView(ListView): | |
model = Order | |
paginator_class = OrderPaginator | |
paginate_by = 20 | |
""" | |
ids = tuple(i.id for i in queryset.only('id')) | |
objects = [None for i in ids] | |
pos_map = dict((obj_id, i) for i, obj_id in enumerate(ids)) | |
bound = set() | |
for cls in classes: | |
for obj in cls.objects.filter(id__in=ids): | |
obj_id = obj.id | |
if obj_id in bound: | |
raise ValueError("Multiple objects exists for id %d" % obj_id) | |
bound.add(obj_id) | |
objects[pos_map[obj_id]] = obj | |
unbound = set(ids).difference(bound) | |
if unbound: | |
for obj in queryset.model.objects.filter(id__in=unbound): | |
objects[pos_map[obj.id]] = obj | |
return objects |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment