【发布时间】: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