Valter Silva
Valter Silva

Reputation: 16656

How to return the latest object inserted in Django?

I'm trying to retrieve the latest inserted object from my model Reading by its field reading.

I'm trying like this:

@csrf_exempt
def get_config(request):
    if request.method == 'POST':
        reading = Reading.objects.latest('reading')
        print reading
        #reading = 10    

        return HttpResponse(json.dumps(str(reading)), content_type="application/json")
    return render(request, 'web/home.html')

And this is my model:

from django.db import models
...
class Reading(models.Model):
    resource = models.ForeignKey(Resource)
    reading = models.IntegerField()
    date = models.DateTimeField('date', auto_now_add=True)

    def __unicode__(self):
        return u'%s | %s' % (self.resource.urn, self.reading)

The problem is that I'm getting the __unicode__ returns regardless of what I'm asking in my views to be returned.

Any ideas or suggestions ?

Upvotes: 0

Views: 179

Answers (1)

catavaran
catavaran

Reputation: 45605

If you want to output the field value of the instance then pass this field to the dumps() instead of the whole object:

json.dumps(str(reading.reading))

You can also omit the str() call if you want to return a number instead of a string:

json.dumps(reading.reading)

Upvotes: 1

Related Questions