我有以下型号:
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实例访问管理器
你能帮忙吗
答案 0 :(得分:6)
管理员仅适用于模型类,而不适用于模型实例。
这将有效:
UserProfile.objects
这不会:
profile = UserProfile.objects.get(pk=1)
profile.objects
换句话说,如果您在UserProfile
的实例上调用它,它将引发您看到的异常。您可以确认一下如何访问经理吗?
来自docs:
管理员只能通过模型类而不是模型实例访问,以强制“表级”操作和“记录级”操作之间的分离
答案 1 :(得分: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()