Is it possible to use Ajax to Update a Single field in a Specific Object? I have an postgres table with lots of records, I want to use a jquery Ajax request to update a single field in a specific object within that table. Can that be done without replacing or reposting the entire record?.
I want this (Gives me a 400 bad request error):
$.ajax({
type: "POST",
url: '/api/MyEndPoint/',
data: {
id: Specific_Record,
Field_To_Update: New_Value,
},
success: function(data){
console.log( 'success, server says '+data);
}
});
Instead of this (which works):
$.ajax({
type: "POST",
url: '/api/MyEndPoint/',
data: {
id: Specific_Record,
Field_To_Update: New_Value,
Field1: SameAsBefore,
Field2: SameAsBefore,
Field3: SameAsBefore,
...
Field16: SameAsBefore,
},
success: function(data){
console.log( 'success, server says '+data);
}
});
*Note: I'm using Django, and could easily do this update in views.py but I want to use Javascript to avoid a page refresh.
Since I'm also using Django Rest Framework, would it be better for me to create a new endpoint that is specific to the field I want to update? ex: /api/DB_Table/Object_id/Field_to_Update
Thanks!
Yes, you can do this using the PATCH HTTP method and it is called a partial update in REST terminology. It is already implemented by default in DRF so you don't have to override any method for that. This is opposed to PUT which is a full update and will require that you add all required fields to the request unless yuou override the default behavior
I think you can in simplest form use the RetrieveUpdateAPIView
generic view provided by Django RestFramework library
This will expose following apis :
GET
: Return
object
PATCH
: Update
the object data ( partially
, as per convention)
PUT
: Update
the object data
Reference : https://www.django-rest-framework.org/api-guide/generic-views/#retrieveupdateapiview
If you also want to support deleting
object, then you can use RetrieveUpdateDestroyAPIView
, this will support DELETE
to delete object
Reference : https://www.django-rest-framework.org/api-guide/generic-views/#retrieveupdatedestroyapiview
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.