Login

more on manager methods

Author:
grahamu
Posted:
February 28, 2007
Language:
Python
Version:
Pre .96
Tags:
managers
Score:
0 (after 0 ratings)

Snippet #2 demonstrated some cool tricks possible with manager methods. This example shows how to assign and use a custom manager method.

In this snippet the belongs_to_user method returns an Account queryset containing only those accounts associated with the specified user. The method is useful because it hides the implementation of User in the Account model.

Line 17 associates the custom manager with the Account model.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from django.db import models
from django.contrib.auth.models import User

################ models ####################

class AccountManager(models.Manager):
    def belongs_to_user(self, user=None):
        qs = super(type(self), self).get_query_set()
        if user:
            return qs.filter(users__username=user)
        else:
            return qs

class Account(models.Model):
    title = models.CharField(maxlength=30, blank=False)
    users = models.ManyToManyField(User, blank=True, null=True)
    objects = AccountManager()

################ views ####################

def user_accounts(request):
    user_acct_qs = Account.objects.belongs_to_user(request.user.username)

More like this

  1. Using manager methods by ubernostrum 8 years, 3 months ago
  2. Fetching top items by ubernostrum 8 years, 3 months ago
  3. Call a manager method on any model with a filter by coleifer 5 years ago
  4. Custom Model Manager Chaining by hunterford 4 years, 10 months ago
  5. Tatsypie: additional list endpoints for custom Model's manager methods by migajek 2 years, 6 months ago

Comments

adurdin (on March 1, 2007):

The first line of belongs_to_user() would be better as:

qs = self.get_query_set()

#

Please login first before commenting.