我应该如何通过python Django从数据库中读取特定用户的特定数据

2024-04-23 13:45:50 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,在我的数据库中,有一个名为BlackList的表,如下所示: enter image description here

该表的型号为:

class BlackList(models.Model):
    name = models.CharField(max_length=1000, null=True, blank=True)
    flag1 = models.BooleanField(default=False)
    flag2 = models.BooleanField(default=False)
   

我想做的是这样的:

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)
    # BLname = Read the username from the table
    # BLflag1 = read the Flag1 for the user
    # BLflag2 = read the Flag2 for the user
    if BLflag1 == True and BLflag2 == True:  
        something will happen 
    elif BLflag1 == True and BLflag2 == False:  
        something will happen
    else:
        # set the Flag1 and Flag2 of this user to True. 

所以,我的问题是

  1. 如何读取特定用户的特定数据,例如,如果用户“aaa”尝试登录,应用程序将读取aaa为True的Flag1和aaa为True的Flag2
  2. 如何为特定用户设置标志,例如,如果用户“bbb”尝试登录,应用程序最终会将Flag1和Flag2设置为True

1条回答
网友
1楼 · 发布于 2024-04-23 13:45:50

您应该首先检查用户是否经过身份验证

user = authenticate(request, username=username, password=password)
if user is not None:
    BLname = user.username
    BLflag1 = user.Flag1
    BLflag2 = user.Flag2
    if BLflag1 and BLflag2:  # since the values are boolean, you don't need to compare them  
        # something will happen 
    elif BLflag1 and not BLflag2:  
        # something will happen
    else:
        user.Flag1 = True
        user.Flag2 = True
        user.save()
else:
    # do something for unauthenticated users

相关问题 更多 >