简体   繁体   中英

In django how to move objects from a sessions foreign key to a user foreign key when the user logs in

I have a model that saves a endusers progress on a task.

class TaskCompleted(models.Model):
   session = models.ForeignKey('sessions.Session', on_delete=models.SET_NULL,blank=True, null=True)
   user = models.ForeignKey(User, blank=True, null=True)
   task = models.ForeignKey(Task, blank=True, null=True)

The enduser might be logged in or might not be. If they are logged I save the it against the user and if they are not I save it against the session.

When the a user logs in I want to find any tasks they have completed while unauthenticated and then update the user foreign key to relate it to their account.

I am finding that the session is destroyed thus setting the session to Null.

I am interested in other's suggestions on how to handle this?

The session data is not destroyed when a user is logged in - the data is saved to a new session (the key is " cycled "). You can still use request.session['mykey'] . You can do a few things to persist/change the ownership of your TaskCompleted instance. One option would be to save the TaskCompleted instance id in the session for anonymous users, and override the login view to assign that instance to the user on successful login. (And if you follow this, you won't need the session = models.ForeignKey() field in your model)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM