0

我有以下模型:

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:无法通过 UserProfile 实例访问管理器

能否请你帮忙

4

2 回答 2

6

管理器仅适用于模型类而不适用于模型实例。

这将起作用:

UserProfile.objects

这不会:

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

换句话说,如果您在 a 的实例上调用它UserProfile,它将引发您看到的异常。您能否确认您是如何访问管理器的?

文档

管理器只能通过模型​​类而不是模型实例来访问,以强制区分“表级”操作和“记录级”操作

于 2009-09-18T16:13:21.923 回答
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()
于 2009-09-18T16:22:49.517 回答