We have a Django project where a User account is created for a person whenever she calls us on the phone. The person may or may not, at a later point, use her account to log in to our website.
Question: How can I tell if a User has ever logged in to our website?
Clarification: I want to answer the question above for hundreds of existing users, not just for new users that are created from this point on.
Thought 1: Check User.last_login. Unfortunately Django initializes last_login to datetime.datetime.now() when the User is created, regardless of whether she ever logged in.
Thought 2: Check if User.last_login matches User.date_joined. Unfortunately Django initializes both these fields to datetime.now(), and they can be a few microseconds apart:
In [1]: u = User.objects.create(username="bla")
In [2]: u.date_joined - u.last_login
Out[2]: datetime.timedelta(0, 0, 23)
Current hack I am using: Assume the user has logged in at least once iff user.last_login - user.date_joined >= datetime.timedelta(seconds=1).
Is there a better way to tell if a User has ever logged in?
I’m going to assume that you’re right when you say that both the
date_joinedandlast_loginare set to the current date on creation, and that for some reason there is enough time elapsed between the two assignments to create a noticeable delta.If that’s the case, then you could take @LAK’s advice and create either a pre_save (and check if the instance’s ID is 0) or post_save (and check the
createdparameter) and manually set thelast_loginfield to eitherNoneor the same value asdate_joined. From there all of your future data is preserved from the one-second fuzziness you seem to despise.As for your existing data, I think that you’re stuck making the best guess with the data you’ve got. I don’t see it as too risky to make the assumption that you’re making. If you wanted to clean it up to be the same as all new data, you could just update your database to set the
last_loginvalue. If you’re using South, this is easy enough to do with a data migration. Otherwise, you could just create a script to run after you deploy the new code changes.I honestly don’t think that it’s a problem that they’re off by a little bit. So long as you’re making the assumption that it’s most likely not humanly possible for a user to log in within the time frame that their account was created, there seems to be little reason to add a bunch of extra work to force it to be an exact match.