Tuesday, 14 May 2013

Django - Get Distinct Data of a Proxy Model

models.py
class SalesPerson(User):
    class Meta:
        proxy = True
    ....

class SalesManager(models.Manager):
    def get_sales_person_list(self, user):
        if user.is_superuser:
            return list(SalesPerson.objects.filter(
                pk__in=list(Sales.objects.values_list('sales_person', flat=True)
                .order_by("sales_person").distinct())))

class Sales(CommonModel):
    ....
    sales_person = models.ForeignKey(User, related_name="sales_by")
    ....
    objects = SalesManager()
    ....
History - Before Optimized
return [SalesPerson.objects.get(pk=obj) for obj in self.get_query_set()
            .values_list('sales_person', flat=True).order_by("sales_person").distinct()] 

1 comment :