Search code examples
pythondjangotastypie

Django update instead of saving


I am using Django 1.7.1 and Tastypie 0.12.1

I currently have a model:

class Geigeki(models.Model):
    class Meta:
        ordering = ['-updated']
    machine = models.ForeignKey(Machine, blank=False)
    client = models.CharField(blank=False, max_length=30)
    authoritative_server = models.GenericIPAddressField(blank=False)
    count = models.BigIntegerField(blank=False, default=0)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    def __unicode__(self):
        return "%s's geigeki measurements" % self.machine.name

When using the REST API, I would like to actually update my count field instead of saving a brand new object.

For this, I would like to be able to search for my object using machine, client and authoritative_server and increment the count field.

Problem is, it doesn't seem like I can search for an object within its own save method. I thought I could use a pre_save signal but I'm not sure that works either.

Does anyone of you have an idea how to do this?

I thank you in advance for your help.


Solution

  • I may not be fully understanding this but, from what I've gathered, we want to query for an object based on 'machine', 'client', and 'authoritative_server' and then be able to update the count for that object.

    Django REST Framework provides the ability to filter on different fields for a model, http://www.django-rest-framework.org/api-guide/filtering. Assuming the Django REST Framework API endpoint for model Geigeki is '/api/v1/geigeki/' we could first filter to get back a list of objects that meets our criteria, Example, /api/v1/geigeki/?machine=1&client=testclient&authoritative_server=127.0.0.1

    You could then take the ID from an object returned from the previous API call, and perform a 'PATCH' request to /api/v1/geigeki//. This 'PATCH' request should only contain the 'count' field.