简体   繁体   中英

How to access property from models into Django Queryset?

I have this model in which I created a property to format DateTimeField. However I can't access/reference it. Tried this so far:

class DataForecast(models.Model):
    date_time = models.DateTimeField()
    rainfall_mm_per_10_min = models.FloatField(null=True)
    wl_observed_m = models.FloatField(null=True)
    wl_forecasted_m = models.FloatField(null=True)

    def __unicode__(self):
        return self.date_time

    @property
    def date_time_formatted(self):
        import datetime
        return self.date_time.strftime('%b %d, %Y %I:%M %p')

And while in my views.py:

formatted = [dataforecast.date_time_formatted for dataforecast in DataForecast.objects.all()]
getall = DataForecast.objects.all().values_list(formatted, "rainfall_mm_per_10_min", "wl_observed_m","wl_forecasted_m")
return HttpResponse(json.dumps(list(getall),cls=DjangoJSONEncoder), content_type='application/json')

It returns an error:

Exception Value: 'list' object has no attribute 'split'

There are two ways of doing this:

add .values()

DataForecast.objects.all().values()

will give you a list to iterate through.

Otherwise remember that the output is an object, so use object.key notation to get the values

values/values_list take optional field arguments only. They wont take query set as arguments.

Set unicode in return value

def __unicode__(self):
    return unicode(self.date_time)

You can directly do this

In [6]: DataForecast.objects.all().values("date_time", "rainfall_mm_per_10_min", "wl_observed_m","wl_forecasted_m")
Out[6]: [{'date_time': datetime.datetime(2015, 3, 27, 6, 5, 36, tzinfo=<UTC>), 'wl_forecasted_m': 2.0, 'rainfall_mm_per_10_min': 1.0, 'wl_observed_m': 2.0}, {'date_time': datetime.datetime(2001, 1, 1, 0, 0, tzinfo=<UTC>), 'wl_forecasted_m': None, 'rainfall_mm_per_10_min': None, 'wl_observed_m': None}]

or better try

In [7]: DataForecast.objects.all().values()
Out[7]: [{'wl_observed_m': 2.0, 'date_time': datetime.datetime(2015, 3, 27, 6, 5, 36, tzinfo=<UTC>), 'wl_forecasted_m': 2.0, u'id': 5, 'rainfall_mm_per_10_min': 1.0}, {'wl_observed_m': None, 'date_time': datetime.datetime(2001, 1, 1, 0, 0, tzinfo=<UTC>), 'wl_forecasted_m': None, u'id': 6, 'rainfall_mm_per_10_min': None}]

Converting to json

In [19]: all = DataForecast.objects.all().values()

In [20]: all
Out[20]: [{'wl_observed_m': 2.0, 'date_time': datetime.datetime(2015, 3, 27, 6, 5, 36, tzinfo=<UTC>), 'wl_forecasted_m': 2.0, u'id': 5, 'rainfall_mm_per_10_min': 1.0}, {'wl_observed_m': None, 'date_time': datetime.datetime(2001, 1, 1, 0, 0, tzinfo=<UTC>), 'wl_forecasted_m': None, u'id': 6, 'rainfall_mm_per_10_min': None}]

In [21]: for i in all: i['date_time'] =  i['date_time'].strftime("%b %d %Y %H:%M:%S")

In [22]: all
Out[22]: [{'wl_observed_m': 2.0, 'date_time': 'Mar 27 2015 06:05:36', 'wl_forecasted_m': 2.0, u'id': 5, 'rainfall_mm_per_10_min': 1.0}, {'wl_observed_m': None, 'date_time': 'Jan 01 2001 00:00:00', 'wl_forecasted_m': None, u'id': 6, 'rainfall_mm_per_10_min': None}]

In [23]: import json

In [25]: json.dumps(list(all))                                                                                                                                                  
Out[25]: '[{"wl_observed_m": 2.0, "date_time": "Mar 27 2015 06:05:36", "wl_forecasted_m": 2.0, "id": 5, "rainfall_mm_per_10_min": 1.0}, {"wl_observed_m": null, "date_time": "Jan 01 2001 00:00:00", "wl_forecasted_m": null, "id": 6, "rainfall_mm_per_10_min": null}]'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM