User manager

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class UserManager(models.Manager):
    def __init__(self, *args):
        try:
            self.fk_field_name = args[0]
        except IndexError:
            self.fk_field_name = None

        super(UserManager, self).__init__()

    def get_query_set(self):
        query_set = super(UserManager, self).get_query_set()
        
        if self.fk_field_name:
            current_user = get_current_user()

            if current_user and not current_user.is_superuser:
                return query_set.filter(**{ '%s__exact' % self.fk_field_name: current_user })

        return query_set

# Example usage

class TestModel(models.Model):
    owner = models.ForeignKey('auth.user')
    objects = UserManager('owner')

More like this

  1. Improved generic foreign key manager 2 by Nomalz 4 years, 6 months ago
  2. Querying on existence of a relationship by ubernostrum 6 years, 8 months ago
  3. Specify a manager for the Admin by kylefox 6 years, 2 months ago
  4. update primary key (and cascade to child tables) by guettli 2 years, 2 months ago
  5. improved generic foreign key manager by carljm 5 years, 7 months ago

Comments

(Forgotten your password?)