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 |
+----+-------------+---------------+
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')
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With