I have a model:

class MyModel(models.Model):
    id = models.IntegerField(primary_key=True)
    recorded_on = models.DateField()
    precipitation = models.FloatField(null=True, blank=True)

in my views I have a query thus:

import datetime

def my_view(request):
    ...
    format = '%Y-%m-%d' 
    sd = datetime.datetime.strptime(startdate, format)
    ed = datetime.datetime.strptime(enddate, format)
    queryset = MyModel.objects.filter((recorded_on__range = (sd, ed)))
    ...

But whenever I try and do anything with the queryset (e.g. json dump, display in template), I get the following error:

    coercing to Unicode: need string or buffer, datetime.date found

I know there must be an easy way to deal with this, but I have not yet found it.

Any help would be much appreciated.

EDIT:

An example of data:

+----+-------------+---------------+
| id | recorded_on | precipitation |
+----+-------------+---------------+
| 24 | 1987-07-02  |          20.7 |
| 33 | 1987-07-11  |           0.4 |
+----+-------------+---------------+
share|improve this question
1  
Please show the actual traceback. Which line is causing the error? – Daniel Roseman Mar 28 '12 at 15:18
    
are you by any change trying to concatenate recorded_on with unicode string using + operator? If so, the way to do it is u"a string" + str(obj.recorded_on) – vartec Mar 28 '12 at 15:23
    
My traceback is somewhat different from the post, as I have simplified it - I suspect this is a general problem. But the line of my code that django complains about is the views.py line which renders to template. Link here: dpaste.com/722851 .I also tried the query in the shell and just trying to print or iterate the queryset gives the same error. – Darwin Tech Mar 28 '12 at 15:30
    
I am not concatenating. As I mentioned, I run the query in the shell and try: >>> list(queryset) which gives the same coercion error. So I guess I need to act directly on the queryset before I can do anything with it. – Darwin Tech Mar 28 '12 at 15:35
up vote 22 down vote accepted

You haven't shown the full code, but I suspect the problem is with your model's __unicode__ method. This needs to return an actual unicode string - if you are just doing return self.recorded_on that will fail with the given error. Try something like return unicode(self.recorded_on), or use strftime to convert to your desired date formatting, for example self.recorded_on.strftime('%Y-%m-%d').

share|improve this answer
1  
Perfect. Thankyou. I actually had no idea the problem could be with the model! – Darwin Tech Mar 28 '12 at 16:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.