1

For example, I have a table called BlackList in the database which looks like this:

enter image description here

and the model of the table is:

class BlackList(models.Model):
    list = models.CharField(max_length=1000, null=True, blank=True)

What I try to do is:

if request.method == "POST":
    username = request.POST.get('username')  # Get username input first
    password = request.POST.get('password')
    user = authenticate(request, username=username, password=password)
    BL = BlackList.objects.values_list('list', flat=True) # Read all data into array
    if username in BL:  # Check if the username is in blacklist
       # Remove this username from the BlackList table

So my question is how to delete the special data for a special, for example, if 'aaa' try to log in, then 'aaa' will be removed or deleted from the BlackList table.

1
  • 1
    Not sure what the end goal is here, but with above code you will remove the user from the blacklist even if he fails to login. Commented Jul 14, 2020 at 19:11

2 Answers 2

2

There is .delete method. I. e. try this:

if BlackList.filter(list=username).exists(): 
    BlackList.objects.get(list=username).delete() 

instead of:

BL = BlackList.objects.values_list('list', flat=True) # Read all data into array 
if username in BL: # Check if the username is in blacklist 
    # Remove this username from the BlackList table

You can read more about that on https://docs.djangoproject.com/en/3.0/topics/db/queries/#deleting-objects and https://docs.djangoproject.com/en/3.0/ref/models/querysets/#exists

Sign up to request clarification or add additional context in comments.

Comments

2

You can use filter() in combination with first() to get the exist username:

blacklist = Blacklist.objects.filter(username=username).first()

(This will return None if there is no match. If you use get(), you will get DoesNotExist error instead -- which is not preferred.)

After that, you can just delete it:

blacklist.delete()

It will take 2 queries (get and delete) to achieve your goal.

An alternative way is to delete it without getting the object:

Blacklist.objects.filter(username=username).delete()

This statement will be execute with only one query which is equals DELETE FROM ... WHERE username='username'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.