开发者

querying in django

I have stored data in the table with respect to dates ie there could be more than one entry for the same month, but when i retrieve them i need to get them as combined result. So is there anyway that i could query it to retrieve the data for a month that is set the range as month in django(view).

edit:

Modifications from my prev post. I need to do it for a year and i do not have a specific start date and end date. I need to set the range for months in a year irrespective of the number of days present. my database would loo开发者_如何学运维k like this:

date        count1     count2  
2011/12/01,   12,          3 
2011/12/03,   3,           6

Now i need to retrieve count1 for the month of december. I need a generic query not just for a particular month with say 30 or 31 or 28 days.


docs

Assuming you have a DateField

class MyModel(models.Model):
    my_date = models.DateField()

query:

import datetime
startdate = datetime.date(...start of some month...)
enddate = datetime.date(...end of some month...)
my_model_in_range = MyModel.objects.filter(my_date__range(startdate,enddate))

edit:

count docs

import datetime

def first_day_of_month(month, year):
    return datetime.date(year, month, 1)

def last_day_of_month(month, year):
    return datetime.date(year, month+1, d.day) - datetime.timedelta(1)

# if you want query for jan 2009: month = 1, year = 2009

first = first_day_of_month(1, 2009)
last = last_day_of_month(1, 2009)

objects_in_jan_2009 = MyModel.objects.filter(my_date__range(first, last))

count = objects_in_jan_2009.count()


After you receive you range, query you model with the following:

YouModel.objects.filter(date__gt='initial date').filter(date__lt='final date')

date should be a field in your model. the __gt and __lt aply a filter for the field to search for values greater and lesser than the parameter passed.


Best way to do it is through raw sql

YourModel.objects.extra(
        select={'values':'select sum(count) as count , extract(month from mymodel_db.date) as date group by date'}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜