Chainsaw
Chainsaw

Reputation: 311

Change variable in views.py after model.method worked - Django

everyone.

I have a global variable in views.py: it is a list of users who voted.

I want to empty that list, after my Author is deleted.

I have a Author.delete method in models.py, which I could use to empty it, but I can't import a list to models.py

views.py

voted_list=[]

models.py

class Author(models.Model):
    def delete(self, *args, **kwargs):
        Option.objects.filter(author_id=self.id).update(author_id=None, votes=0)
        super().delete(*args, **kwargs)

Or may I import my 'delete' method to views, something like:

views.py

if Author.delete():
    voted_list=[]

EDIT I needed to be more clear with my question. I have a method in views: def

vote(request, author_id):
    global voted_list
    author = get_object_or_404(Author, pk=author_id)
    a= LogEntry.objects.log_action(
    user_id         = request.user.pk, 
    content_type_id = ContentType.objects.get_for_model(Option).pk,
    object_id       = Option.pk,
    object_repr     = force_text(Option), 
    action_flag     = CHANGE
)
    print("Voted:",a.user_id)
    voted_list.append(User.objects.get(pk=a.user_id))

I just want to pass to a template list of user_id who voted. But after a deletion of Author empty it. I dont want to use db changes, because in my current state I think i've overcomplicated them

Thank you.

Upvotes: 0

Views: 324

Answers (2)

Chainsaw
Chainsaw

Reputation: 311

I resolved my problem using LogEntry function

Upvotes: 0

KrazyMax
KrazyMax

Reputation: 959

First of all, please be aware that it is a bad practice to have global variables for such use.

You code looks a bit weird in my opinion: when you delete an Author (which object I assume is a foreign key for Option?), then automatically it sets the value of this ForeignKeyField to None. So, setting manually author_id=None does not feel right (it is like you are doing something not required).

What does voted_list relate to?

Something I would suggest is to set for each class you need to know who voted for (is that Option?), a ManyToManyField called authors_who_voted_for (for instance), and add manually any Author instance who actually voted for said Object. That way, if one Author is to be deleted, it will be automatically removed from authors_who_voted_for. Wouldn't that be a better solution for you?

Upvotes: 1

Related Questions