【问题标题】:Django: Extracting the value from a Queryset and store in a variable for filtering later onDjango:从查询集中提取值并存储在变量中以供稍后过滤
【发布时间】:2019-11-11 16:51:54
【问题描述】:

我想从查询集中提取一个值,然后将其存储在一个变量中,以便以后可以将其用作过滤条件。我该怎么做?

这个 userprofile 模型链接到 User 模型,因此 User.id 将与 userprofile 模型中的 user_id 相同:

class userprofile(models.Model):
    user=models.OneToOneField(User, ...)
    age=....
    user_race=models.Charfield(.....)

我想获取该用户的种族并将其存储为变量“x”,所以当我查询以下方式时:

x = userprofile.objects.filter(user_id=request.user.id).user_race
#doesn't seem to get the race of this user...how to get it?

问题:“x”现在是字符串变量还是字典列表形式的查询集?

然后我想在使用以下模型过滤另一个查询集时使用“x”作为标准:

class cuisines(models.Model):
    portion=....
    race=models.Charfield(.....)

查询:

y = cuisines.objects.filter(race='x')       #This is to get all the results as long as the race of the user matches the race value in the cuisines model.

请帮助我更好地理解我在这个逻辑/过程中出错的地方。

谢谢。

【问题讨论】:

  • 使用get 而不是filter。 (实际上,如果你运行了这段代码,你会得到一个 AttributeError;x 根本不存在。)
  • This 可以帮助您。
  • @DanielRoseman:如果x 不存在,那么y = cuisine.objects.filter(race=x) 肯定也不起作用。那么如何通过用户配置文件访问用户种族的价值呢?然后稍后使用它来过滤美食模型?

标签: python django filter parameter-passing extract


【解决方案1】:

您只需要像这样更改您的查询:-

user_profile = userprofile.objects.get(user__id=request.user.id)
x = user_profile.user_race

那么,下一个查询应该是这样的:-

y = cuisines.objects.filter(race=x)

【讨论】:

  • 好的,谢谢。我尝试了类似的方法,但最初并没有奏效。再次检查我的用户配置文件模型(userprofile.user_race)值后,我意识到字符串中包含一个\r,即'japanese\r'。因此,整个字符串将存储在 x 变量中,这当然与 Cuisines.race 中的值(即“japanese”)不同。
  • 宁可使用user_id 而不是user__id 以避免不必要的连接。
猜你喜欢
  • 1970-01-01
  • 2018-05-12
  • 2017-12-26
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
  • 2022-01-05
相关资源
最近更新 更多