Search code examples
pythondjangodjango-orm

Django - annotating a field to a model query which adds a datefield value to an existing model field in views


I want to add a field to my model in views without adding it to the database using the annotate function.

user_accounts_extension.objects.filter(types='trial').annotate(expire_date=duration + datetime.timedelta(days=180))

The model user_accounts_extension is an extension of the included auth models.

"Duration" is a datefield which represents the date when the account is closed.

I want my view to render this field + 180 days to my template - but the above code doesn't work. I've also tried:

 user_accounts_extension.objects.filter(types='trial').annotate(expire_date='duration' + datetime.timedelta(days=180))

To no avail. Is this possible to do, or do I need to add a new field to my model?

EDIT:

For context, here is an example of the view:

def overview(request):
    accounts = user_accounts_extension.objects.filter(types='trial').annotate(expire_date=duration + datetime.timedelta(days=180))
    return render(requests, 'overview.html'{'accounts': accounts})

In my template, I want to iterate through the properties of the accounts, so I want to add a customizable property - if possible - to the query.


Solution

  • Solution:

    I added a boolean dummy-variable to the model, and modified it's instance from the query in the view:

    def overview(request):
        accounts = user_accounts_extension.objects.filter(types='trial')
        for account in accounts: 
            if account.expire_date + datetime.timedelta(days=180) <= datetime.date.today():
                account.deletion_trigger = True
    return render(requests, 'overview.html'{'accounts': accounts})
    

    This only modifies the instance that is rendered to the template, and nothing is saved to the database.