【问题标题】:Problems with django managersdjango 管理器的问题
【发布时间】:2009-09-18 15:39:34
【问题描述】:

我有以下型号:

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

请帮忙

【问题讨论】:

    标签: django django-models django-managers


    【解决方案1】:

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

    这将起作用:

    UserProfile.objects
    

    这不会:

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

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

    来自docs

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

    【讨论】:

      【解决方案2】:
      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()
      

      【讨论】:

        猜你喜欢
        • 2015-01-29
        • 2011-05-16
        • 2011-08-08
        • 2012-12-23
        • 2011-06-17
        • 2021-10-14
        • 2011-04-20
        • 1970-01-01
        • 2020-08-02
        相关资源
        最近更新 更多