2009-09-18 58 views
0

我有以下型號:問題和Django經理

class UserProfile(models.Model): 
    """ 
    User profile model, cintains a Foreign Key, which links it to the 
    user profile. 
    """ 
    about = models.TextField(blank=True) 
    user = models.ForeignKey(User, unique=True) 
    ranking = models.IntegerField(default = 1) 
    avatar = models.ImageField(upload_to="usermedia", default = 'images/js.jpg') 
    updated = models.DateTimeField(auto_now=True, default=datetime.now()) 
    is_bot = models.BooleanField(default = False) 
    is_active = models.BooleanField(default = True) 
    is_free = models.BooleanField(default = True) 
    objects = ProfileManager() 

    def __unicode__(self): 
     return u"%s profile" %self.user 

而且經理

class ProfileManager(models.Manager): 
    """ 
    Stores some additional helpers, which to get some profile data 
    """ 
    def get_active_members(self): 
     ''' 
     Get all people who are active 
     ''' 
     return self.filter(is_active = True) 

的時候,我嘗試調用像UserProfile.obgets.get_active_members()

我得到

raise AttributeError, "Manager isn't accessible via %s instances" % type.__name__ 

AttributeError的:經理通過用戶配置情況下是無法訪問的

能否請你幫

回答

6

經理們只能在模型類可用的以及模型實例

這將工作:

UserProfile.objects 

這不會:

profile = UserProfile.objects.get(pk=1) 
profile.objects 

換句話說,如果你是在一個實例UserProfile調用它,它會引發異常你看到。你能否確認你是如何訪問經理的?

docs

Managers are accessible only via model classes, rather than from model instances, to enforce a separation between "table-level" operations and "record-level" operations

1
class ActiveUserProfileManager(models.Manager): 
     def get_query_set(self):   
      return super(ActiveUserProfileManager , self).get_query_set().filter(active=True, something=True) 


class UserProfile(models.Model): 
    objects = models.Manager() 
    active_profiles = ActiveUserProfileManager() 


UserProfile.active_profiles.all() 
UserProfile.active_profiles.filter(id=1) 
UserProfile.active_profiles.latest()