Alan Tingey Alan Tingey - 1 year ago 71
MySQL Question

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.

Answer Source

campaignnoquery is, as the error says, a QuerySet object (in this case it holds UserSelection instances).

Your error is treating it as an instance of a single UserSelection object.

Are you sure this filter will always return a single object? if so, you can use get instead.

If not, what are you expecting campaignnoquery.campaignno to return? (considering campaignnoquery is a group of UserSelection objects).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download