[Django]-Complex reverse query in Django

3👍

For the simple case you’ve given, the solution is simple:

B.objects.filter(a__c__isnull=False)

For the actual query, here’s my try:

Indirect.objects.filter(direct__id__in=
    zip(*CanRead.objects.filter(
           content_type=ContentType.objects.get_for_model(Direct)
        ).values_list('id'))[0])

But this way is very slow: you extract IDs from one queryset, then do a query with

where id in (1, 2, 3, ... 10000)

Which is VERY SLOW. We had a similar issue with joins on generic foreign keys in our project and decided to resort to raw queries in the model manager.

class DirectManager(Manager):
    def can_edit(self, user):
        return self.raw(...)

I’d also recommend checking out the per-row permissions framework in Django 1.3.

1👍

access control models are not that simple…
use a well-known access control model such as:
DAC/MAC
or
RBAC
also there is a project called django-rbac.

👤Kambiz

Leave a comment