gpt4 book ai didi

python - App Engine 查询用户

转载 作者:行者123 更新时间:2023-12-01 02:54:59 24 4
gpt4 key购买 nike

我的数据存储中有用户模型,其中包含一些属性:

enter image description here

我需要查询按 company 属性过滤的所有用户。

所以,就像我通常做的那样,我这样做:

from webapp2_extras.appengine.auth.models import User

employees = User.query().filter(User.company == self.company_name).fetch()

这给了我:

AttributeError: type object 'User' has no attribute 'company'

当我这样做时:

employees = User.query().filter().fetch()

它没有给我任何错误,并显示包含所有用户的列表。

如何按字段查询?谢谢

最佳答案

你的问题有点误导。您询问如何按字段查询,您已经使用正确的语法进行了查询。正如 Jeff O'Neill 指出的那样,问题是您的 User 模型没有该 company 字段,因此您的按字段查询尝试会导致错误。 (Here is some ndb documentation 如果您还没有的话,您一定应该仔细阅读并添加书签。)可以通过三种方法来解决您的缺失字段问题:

  1. User 模型进行子类化,正如 Jeff 在他的回答中所示。这既快速又简单,可能是您想要的最佳解决方案。
  2. 创建您自己的用户模型,与 webapp2 完全分开。仅从您的问题来看,这对于您想要的东西来说可能有点过分了,因为您必须编写 webapp2 用户已经为您处理的大部分自己的身份验证代码。
  3. 创建一个包含额外用户信息的新模型,并具有包含相应用户 key 的 key 属性。看起来像这样:

    class UserProfile(ndb.Expando):
    user_key = ndb.KeyProperty(kind='User', required=True)
    company = ndb.StringProperty()
    # other possibilities: profile pic? address? etc.

    像这样的查询:

    from models.user_profile import UserProfile
    from webapp2_extras.appengine.auth.models import User
    from google.appengine.ext import ndb

    # get the employee keys
    employee_keys = UserProfile.query(UserProfile.company == company_name).fetch(keys_only=True)

    # get the actual user objects
    employees = ndb.get_multi(employee_keys)

    此解决方案的作用是将用于身份验证的用户模型(webapp2 的用户)与保存额外用户信息的模型(UserProfile)分开。如果您想为每个用户存储个人资料图片或其他相对大量的数据,您可能会发现此解决方案最适合您。

注意:您可以将过滤条件放在 .query() 括号中以简化操作(我发现我很少使用 .filter() 方法):

# long way
employees = User.query().filter(User.company == self.company_name).fetch()

# shorter way
employees = User.query(User.company == self.company_name).fetch()

关于python - App Engine 查询用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44309305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com