开发者

Django: Django QuerySet with Date SELECT working erratically

Up until a couple days ago I have been using the following query succesfully. The following query has always returned the data it was supposed to return:

try:
  totals = MyObject.objects.get(date=report_date)
except MyObject.DoesNotExist:
  return HttpResponse('Could not find totals from %s' % (report_date))

A couple days ago this query began returning an empty QuerySet, even though data Does exist for the day I am requesting.

I am getting the date from report_date = date.today().strftime('%Y-%m-%d') or from a form

if request.method == 'POST':
  form = DateForm(request.POST)
  if form.is_valid:
    report_date = request.POST['date']

The Model is simple datefield()

class MyObject(models.Model):
  """Total numbers for a specific day"""
  date = models.DateField()
  ... remaining fields ...

I have verified through the shell that there is in fact data for todays date in TotalTransactions. I have been using this code for months with no problem. I made a work around yesterday by querying totals = MyObject.objects.get(date__gte=report_date, date__lte=report_date) but this morning it no longer worked!! This morning I then tried the original que开发者_如何学Gory of date=report_date and that worked!

So my question is: Has anyone had this problem before?? Can anyone see something in my code that i am missing? Any suggestions on more workarounds? I appreciate your time.


why converting to the string? you do not have a control on how date is converted, eg. locale issues.

switch to date objects and set in views only:

report_date = date.today()

and get data from the form's cleaned_data dict:

report_date = form.cleaned_data['date']


The fact that date-based queries work one day but not the next is suggestive. I suspect - although you haven't shown enough code to be sure - that you have inadvertently set some defaults somewhere, which are being persisted across requests.

For example, if you do this:

class MyModel(models.Model):
    my_date_field = model.DateField(default=datetime.date.today())

the value of the field default is evaluated when the server process starts, and remains the same as long as the process is running - which can be days or weeks.

The same is true if you do this in a view:

def my_view(request, date=datetime.date.today()):
    ... do something with date ...

because view arguments, again, are evaluated when the view is defined, not when it is executed, and therefore the value will remain the same as long as the process exists.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜