django rest framework - always INSERTs, never UPDATES

2024/10/4 17:30:49

I want to be able to UPDATE a user record by POST. However, the id is always NULL. Even if I pass the id it seems to be ignored

View Code:

JSON POSTED:

{"id": 1, "name": "Craig Champion", "profession": "Developer", "email": "[email protected]"
}@api_view(['POST'])
def get_purchase(request):"""Gets purchase records for a userPurchase collection is returned"""user = User();serializer = UserSerializer(user, data=request.DATA)if serializer.is_valid():#The object ALWAYS has ID = nothing at this pointserializer.save()return Response(serializer.data, status=status.HTTP_200_OK)else:return Response(serializer.errors,   status=status.HTTP_400_BAD_REQUEST)

ModelSerializer

class UserSerializer(serializers.ModelSerializer):class Meta:model = Userfields = ('id', 'name', 'profession', 'email', 'password', )write_only_fields = ('password' , )

Model

class User(models.Model):name = models.CharField(max_length=30, null=True, blank=True)profession = models.CharField(max_length=100, null=True, blank=True)email = models.EmailField()password = models.CharField(max_length=20, null=True, blank=True)def __unicode__(self):return self.name

How can I force the savechanges to update and see the ID?

Answer

You need to use partial=True to update a row with partial data:

serializer = UserSerializer(user, data=request.DATA, partial=True)

From docs:

By default, serializers must be passed values for all required fieldsor they will throw validation errors. You can use the partial argumentin order to allow partial updates.

https://en.xdnf.cn/q/70579.html

Related Q&A

Copy fields from one instance to another in Django

I have the following code which takes an existing instance and copies, or archives it, in another model and then deletes it replacing it with the draft copy. Current Codedef archive_calc(self, rev_num,…

Python selenium get Developer Tools →Network→Media logs

I am trying to programmatically do something that necessarily involves getting the "developer tools"→network→media logs. I will spare you the details, long story short, I need to visit thou…

deep copy nested iterable (or improved itertools.tee for iterable of iterables)

PrefaceI have a test where Im working with nested iterables (by nested iterable I mean iterable with only iterables as elements). As a test cascade considerfrom itertools import tee from typing import …

ImportError: No module named cv2.cv

python 3.5 and windows 10I installed open cv using this command :pip install opencv_python-3.1.0-cp35-cp35m-win_amd64.whlThis command in python works fine :import cv2But when i want to import cv2.cv :i…

Why arent persistent connections supported by URLLib2?

After scanning the urllib2 source, it seems that connections are automatically closed even if you do specify keep-alive. Why is this?As it is now I just use httplib for my persistent connections... bu…

How to find accented characters in a string in Python?

I have a file with sentences, some of which are in Spanish and contain accented letters (e.g. ) or special characters (e.g. ). I have to be able to search for these characters in the sentence so I can…

Import error with PyQt5 : undefined symbol:_ZNSt12out_of_rangeC1EPKc,versionQt_5

I had watched a video on YouTube about making your own web browser using PyQt5. Link to video: https://youtu.be/z-5bZ8EoKu4, I found it interesting and decided to try it out on my system. Please note t…

Python MySQL module

Im developing a web application that needs to interface with a MySQL database, and I cant seem to find any really good modules out there for Python.Im specifically looking for fast module, capable of h…

How to calculate correlation coefficients using sklearn CCA module?

I need to measure similarity between feature vectors using CCA module. I saw sklearn has a good CCA module available: https://scikit-learn.org/stable/modules/generated/sklearn.cross_decomposition.CCA.h…

cant open shape file with GeoPandas

I dont seem to be able to open the zip3.zip shape file I download from (http://www.vdstech.com/usa-data.aspx)Here is my code:import geopandas as gpd data = gpd.read_file("data/zip3.shp")this …