开发者

Django development - Accessing results from a model

Once i have loaded my model and filtered it if i need to, how do i then access the results? I can find loads of examples on querying and filtering the model but none on how to work with the object thats returned?

My model looks like this...

class Ratecard(models.Model):
    region = models.CharField(max_length=32)
    reportSuite = models.CharField(max_length=32)
    RP_UniqueUsers = models.IntegerField()
    RP_PageImpressions = models.IntegerField()
def __str__(self):
    return self.region

and my simple index view is like this...

def index(request):

    reportSuites = Ratecard.objects.all()

    return render_to_response('index.html', locals())

What i want to be able to do is filter based on region and then access the values in the other fields开发者_StackOverflow中文版... This is something very simple in PHP but i know hardly any python / django so any help would be amazing.

Right, so what i need to do is perform some calculations on what is returned, so i could do... reportSuite = Ratecard.objects.get(region="Liverpool") answer = reportSuite.RP_UniqueUsers * 100

Is that correct?


If you wish to use instance, something like:

reportSuite = Ratecard.objects.get(id=??)
reportSuite.region

reportSuite = Ratecard.objects.all()
for reportSuite in reportSuites:
    reportSuite.region

But if you wish to use the instance(es) in your page directly, you must do it in the template

return render_to_response('template_name', {'reports':reportSuites})

In the template:

{%for report in reports%}
    {{report.region}}
{%endfor%}

Information about render_to_rsponse Info about Django Templates

UPDATE: yes, you can do it, but best place for such things are your view functions... So:

answer = reportSuite.RP_UniqueUsers * 100
return render_to_response('template_link', {'reports':reportSuites, 'ans':answer})

And in your tepmlate, you can use

{{ans}}

to show your result...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜