0

I am trying to decipher how .update() is being used in this context. Here's the code:

 user = User.objects.get(username=username) userializer = UserSerializer(user) other = Other.objects.get(other=userializer.data['user_id']) oserializer = OtherSerializer(other) userdata = userializer.data userdata.update({'target_id': oserializer['target'].value}) 

And here's the UserSerializer:

class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('user_id', 'username', 'sec_question_1', 'sec_answer_1', 'sec_question_2', 'sec_answer_2', 'sec_question_3', 'sec_answer_3', 'roles') 

As you can tell, target_id is not in the serializer.

So I am wondering how the original model row is being updated by this .update() method, and I'm wondering where the documentation for it is - is this the QuerySet .update()? Is it the serializer .update() (which doesn't appear to exist - is there a default?)

I'm trying to rewrite this to be more robust and I'm having a hard time understanding what is going on.

2 Answers 2

2

It is neither of those, and it is not affecting the row at all.

The output of the serializer is a standard Python dictionary. Dicts have an update method; that is what is being called here.

That code could just as well have been written:

userdata['target_id'] = oserializer['target'].value 
Sign up to request clarification or add additional context in comments.

1 Comment

That makes so much more sense. I'll accept this as soon as I can.
0

The .update() used here is not the Django QuerySet.update() but a Python dictionary .update().

oserializer = OtherSerializer(other) # initialize the serializer with the instance userdata = userializer.data # get serialized representation of the object 

The above 2 lines initialize the serializer with the instance. When you do serializer.data with an instance passed to it, it will return a dictionary containing the serialized represention of that instance. So userdata is a Python dictionary or more precisely an OrderedDict.

Now, when you call .update() on userdata with a dictionary argument, it will add another key target_id to the userdata dictionary.

The below lines are equivalent.

userdata.update({'target_id': oserializer['target'].value}) userdata['target_id'] = oserializer['target'].value 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.