1👍
try at first check if there is Myuser
instance if not create new one, but if there is Myuser
class instance for that user, then update that instance by doing this code.
u=User.objects.get(username='barkthinks')
try:
myuser_instance = Myuser.objects.get(user=u)
myuser_instance.points += 5
myuser_instance.save()
except ObjectDoesNotExist:
Myuser.objects.create(user=u, points=10)
0👍
Get the Unique Myuser instance and update the model instead
u=User.objects.get(username=request.user.username)
myuser = Myuser.objects.get(user=u)
myuser.points += 5
myuser.save()
- [Answered ]-Django Crispy Form with Toggle switch element
- [Answered ]-How to make datetime callable in python module?
- [Answered ]-Docker is not saving django media files into project 'media' directory on production
0👍
to update any instance of a model,
variable = Models.objects.filter(conditions).update(attribute_to_update = update_value)
get the instance of the model using filter and condition, then use the .update to update values
models.py :
class Myuser(models.Model):
user=models.OneToOneField(User, on_delete=models.CASCADE)
points=models.IntegerField(default=1)
views.py :
u=User.objects.get(username='barkthinks')
new_user_instance = Myuser.objects.create(user = u , points=10)
And then in the view.py post_new() function,
my_user = MyUser.objects.get(user__id = request.user.id)
temp = my_user.points
updated_instance = Myuser.objects.get(User__id = request.user.id).update(points = temp + 10)
- [Answered ]-Django forms how to initialze only not required field instead of passing all required fields
- [Answered ]-Django Class based view filtering queryset but not?
Source:stackexchange.com