Reputation: 41
For example, I have a table called BlackList in the database which looks like this:
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.
Upvotes: 1
Views: 118
Reputation: 535
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'
Upvotes: 2
Reputation: 579
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
Upvotes: 2