2021年3月17日星期三

django save a new instance of object

I am trying to update a user "karma points" whenever a user posts something. For this, i first created a new model called Myuser that allows for points property:

class Myuser(models.Model):      user=models.OneToOneField(User, on_delete=models.CASCADE)      points=models.IntegerField(default=1)  

And then in my view.py post_new() function, I tried to update the score:

u=User.objects.get(username=request.user.username)  u.myuser.points=u.myuser.points+5  u.save()  

but then i notice that rather than update the points field, it just saves a new instance with the same user id but updated score. I thought .save() is supposed to update exisiting copy.

This is what i did for object initiation

u=User.objects.get(username=request.user.username)  Myuser.objects.create(user_id=u.id, points=1)  
https://stackoverflow.com/questions/66684331/django-save-a-new-instance-of-object March 18, 2021 at 11:29AM

没有评论:

发表评论