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

2024-09-27 04:19:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从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”现在是一个字符串变量还是一个字典列表形式的查询集

然后我想在使用以下模型筛选另一个查询集时使用“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.

请帮助我更好地理解我在这个逻辑/过程中哪里出错了

谢谢你


Tags: theto用户模型idgetmodelmodels
1条回答
网友
1楼 · 发布于 2024-09-27 04:19:47

你只需要像这样改变你的查询this:- 你知道吗

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

那么,下一个查询应该是this:- 你知道吗

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

相关问题 更多 >

    热门问题