BoJack Horseman
BoJack Horseman

Reputation: 4450

Delete multiple users with end date

I have users who shall be deleted when they hit their contract end date + 2 month. What I mean is, that if a user has the enddate 2016/03/15, I want to delete him when the date is 2016/05/15 or more. I thought about using the filter option, but I am not sure what condition for the filter I should set.

I have a model User

class User(models.Model):
    username = models.CharField(unique=True, primary_key=True)
    ...

And a model where we have stuff stored like created by, modified by.... and the end date

class AccessTimes(models.Model):
    username = models.ForeignKey(User, db_column='username')
    ...
    endtime = models.DateTimeField(null=True, blank=True)
    ...

This is my current view:

def delete_multiple_users(request):
    """
    Deletes the users in a certain timespan and revokes all grants
    """
    users = User.objects.filter(???).delete()
    ...

What filter option/options do I need to use to make this work? Help is highly appreciated!

Upvotes: 2

Views: 84

Answers (2)

Rafal_Szymanski
Rafal_Szymanski

Reputation: 24

Using field named username in AccessTimes class as ForeignKey to User class can be confusing for a while. Username field is declared by User class so it's little more readable to name field according to class_name this field is related to.

class User(models.Model):
    username = models.CharField(...)
    # ...

class AccessTimes(models.Model):
    user = models.ForeignKey(User)
    # ...

Relating user field of AccessTimes class to User class by ForeignKey can be confusing as well. User doesn't access many times probably. Wouldn't be bad idea to resign of AccessTimes class entirely and use UserProfile class instead with appropriate arguments assigned.

class UserProfile(models.Model):
    endtime = models.DateTimeField()
    # ...

Relating UserProfile class to User class seems to be obvious.

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    endtime = models.DateTimeField()
    # ...

Filtering users is much simpler thanks to UserProfile class.

UserProfile.objects.filter(...)

Filtering users which endtime passed two months becomes intuive.

today = datetime.date.today()
two_months_ago = today - timedelta(days = 60)
users_to_delete = UserProfile.objects.filter(endtime__lt = two_months_ago)

Hope it helps. Let me know if not. PLUR.

Upvotes: -1

ilse2005
ilse2005

Reputation: 11439

You can use timedelta for this. This will delete all users whose endtime is more than 2 months ago. As AccessTimes has a ForeignKey to User you also have to use reverse relationships:

import datetime
# date 2 months ago
delete_date = datetime.date.today() - datetime.timedelta(2*365/12)
User.objects.filter(accesstimes__endtime__lte=delete_date).delete()

Upvotes: 2

Related Questions