[Django]-Django: How would one organize this big model / manager / design mess?

7👍

✅

There are two closely related problems when it comes to Django.

One is row level permissions where users/accounts need specific permission to view a specific row (object) in a table, as opposed to normal Django auth framework which has table level permissions.

The project you linked to is one of several projects trying to implement row permissions. django-granular-permissions is another and a third (my favorite and the most active/maintained) is django-authority.

The upcoming release of Django 1.2 will have hooks making row-level permissions easier to implement, and the author of django-authority will work on integrating his project.

The second related problem is something called multi-tenant database which is a variation on row permissions. In this scheme you might have multiple users from a single company, for example, who all have access to data for that company but not other companies (tenants).

I don’t think this is what you’re looking for but you might be able to use some of the same techniques. See how to enforce account separation in Django and multi-tenant django applications. Both have really sparse answers but are a starting point as well as looking at multi-tenant architecture for Rails apps and this article.

As for a more specific answer to your question I think you should either use django-authority or write a custom manager and use the record ownership screener during development to verify your queries aren’t bypassing the custom manager.

2👍

The basic problem here is, even though you don’t use django.contrib.auth that information about the current logged in user is only available in the view and never in the model, because this information is bound to a request. So you will always have to do something like this in the view:

def some_view(request):
    account = get_account_by_request(request)

Then you can use the account to filter models. You can always make this approach more elegant by using a middleware or a decorator but beware that it doesn’t get too tricky. Your design might break at unexpected points (happened to me) because of too much multiple inheritances with inherited managers and the like. Keep it simple and predictable.

1👍

In order to get current user into your code, you can use threadlocals middleware but there isn’t anything fancy about that, just one big hack, so watch out 🙂

Personally, i think it’s bad to put that kind of logic into models, because they’re just data and should not be aware of such things.

Leave a comment