Python Django:从Queryset中提取值并存储在变量中,以便以后进行筛选

Python Django:从Queryset中提取值并存储在变量中,以便以后进行筛选,python,django,filter,parameter-passing,extract,Python,Django,Filter,Parameter Passing,Extract,我想从queryset中提取一个值,然后将其存储在一个变量中,以便以后可以将其用作筛选条件。我该怎么做 此userprofile模型链接到用户模型,因此User.id与userprofile模型中的User\u id相同: class userprofile(models.Model): user=models.OneToOneField(User, ...) age=.... user_race=models.Charfield(.....) 我想获取该用户的种族并将

我想从queryset中提取一个值,然后将其存储在一个变量中,以便以后可以将其用作筛选条件。我该怎么做

此userprofile模型链接到用户模型,因此User.id与userprofile模型中的User\u 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”现在是字符串变量还是字典列表形式的查询集

然后,在使用以下模型筛选另一个queryset时,我想使用“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.
请帮助我更好地理解我在这个逻辑/过程中哪里出错了


谢谢。

您只需按如下方式更改查询:-

user_profile = userprofile.objects.get(user__id=request.user.id)
x = user_profile.user_race
y = cuisines.objects.filter(race=x)
然后,下一个查询应该是这样的:-

user_profile = userprofile.objects.get(user__id=request.user.id)
x = user_profile.user_race
y = cuisines.objects.filter(race=x)

使用
get
not
filter
。(实际上,如果你运行了这个代码,你会得到一个AttributeError;
x
根本不存在。)可以帮你解决这个问题。@DanielRoseman:如果
x
不存在,那么
y=courine.objects.filter(race=x)
肯定也不起作用。那么,我如何通过userprofile访问用户的种族价值呢?然后用它来过滤烹饪模型?是的,谢谢。我试过类似的方法,但一开始没用。再次检查我的userprofile模型(userprofile.user_race)值后,我意识到字符串中包含一个
\r
,即“japanese\r”。因此,整个字符串将被存储在
x
变量中,该变量当然与Cuisines.race(即“japanese”)中的值不同。而是使用
user\u id
而不是
user\u id
来避免不必要的连接。