[英]Django Query - How to use the objects.filter results
If I use the following code it works perfectly: 如果我使用以下代码,则效果很好:
campaignnoquery = UserSelection.objects.filter(user=349).order_by('-campaignno')[:1]
for x in campaignnoquery:
test2 = x.campaignno
However, when I try: 但是,当我尝试:
campaignnoquery = UserSelection.objects.filter(user=349).order_by('-campaignno')[:1]
test1 = campaignnoquery.campaignno
I get the following error: 我收到以下错误:
test1 = campaignnoquery.campaignno
AttributeError: 'QuerySet' object has no attribute 'campaignno'
I am sure it is something basic and I could just crack on with the one that worked but I am just intrigued on whats happening. 我确信这是基本的东西,我可以继续尝试一下,但是我对发生的事情很感兴趣。
Many thanks in advance, Alan. 预先感谢,艾伦。
campaignnoquery
is, as the error says, a QuerySet
object (in this case it holds UserSelection
instances). 如错误所述, campaignnoquery
是一个QuerySet
对象(在这种情况下,它包含UserSelection
实例)。
Your error is treating it as an instance of a single UserSelection
object. 您的错误是将其视为单个UserSelection
对象的实例。
Are you sure this filter
will always return a single object? 您确定此filter
将始终返回单个对象吗? if so, you can use get
instead. 如果是这样,则可以使用get
代替。
If not, what are you expecting campaignnoquery.campaignno
to return? 如果没有,你有什么期待campaignnoquery.campaignno
来回报? (considering campaignnoquery
is a group of UserSelection
objects). (考虑campaignnoquery
是一组 UserSelection
对象)。
You are referencing the wrong object! 您引用的对象错误!
When looping through campaignnoquery, x becomes campaignnoquery[0], campaignnoquery[1], etc... 遍历Campaignnoquery时, x变为campaignnoquery [0],campaignnoquery [1]等。
Try referencing it like this: 尝试像这样引用它:
test1 = campaignnoquery[0].campaignno
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.