Home > Software design >  How can I update a OnetoOne related models instance in restframework?
How can I update a OnetoOne related models instance in restframework?

Time:11-11

I have two related model a user model and profile model.

here's how the data looks like

{
    "id": 2,
    "phone_number": 9843945748,
    "email": "[email protected]",
    "profile": {
        "first_name": "Updated",
        "last_name": "Updated",
        "avatar": null,
        "date_of_birth": "1995-22-01"
    }
}

How do I override update() method in serializer to just updated the profile fields. bypassing the USER MODEL required field which is email, phone_number.

CodePudding user response:

I think If the id is of user than you can simple do in this way

def update(self,request):
    try:
       profile=Profile.objects.get(user__id=request.user.id)
    except Profile.DoesnotExist:
        raise ValidationError("No user found for following id")
    profile.first_name= "Your name"
    profile.last_name ="Your last name"
    profile.save()

This might not be exact function but the main core logic can be this

  • Related