UserComputedInfo
model has a one-to-one relationship with CustomUser
model.
I want to update or create a record in UserComputedInfo
during a form update to CustomUser
. I managed to create/update a record in views.py
Here is the code;
from .models import UserComputedInfo
def profile(request, username):
if request.method == "POST":
user = request.user
form = UserUpdateForm(request.POST, request.FILES, instance=user)
if form.is_valid():
user_form = form.save()
# How to save post_code to copy_input in UserComputedInfo model
user_computed_info_instance = UserComputedInfo(user_id=user.id)
user_computed_info_instance.copy_input = 1.18 # or whatever value to be assigned
user_computed_info_instance.save()
messages.success(request, f'{user_form.username}, Your profile has been updated!')
return redirect("profile", user_form.username)
return redirect("homepage")
This is a follow-up question to a flawed answer I posted to my own past question. Save values into another database table with one-to-one relationship in Django during form update
The answer works the first time when a new record is being created. However, it fails to work the second time profile()
is run because there is already an existing record.
How do I modify profile()
such that a new record will be created if there is no existing record and an update will be made if the record already exists?
I am using Django v4, python v3.9, sqlite database on Windows 10
CodePudding user response:
You can use Django's get_or_create
Model method, leaving rest of the logics untouched.
user_computed_info_instance, created = UserComputedInfo.objects.get_or_create(user_id=user.id)
It'll create the object first time but will get the existing object next time for the same id
.