如何在models.py Django中访问类“atribute”中的值

2024-04-25 00:39:31 发布

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

我想使用views.py中的函数更改用户名和问题。这是my models.py:

class Choice(models.Model):
    username = models.ForeignKey(Users, null=True, on_delete=models.CASCADE)
    question = models.ForeignKey(Questions, null=True,  on_delete=models.CASCADE)
    answer = models.CharField(null=True,max_length=50)

我还想使用以下行更改内部用户名选项:

 if username == str(Users.objects.latest('name')):
             Choice.objects.username = Users.objects.latest('name')

是否有类似Choice.objects.something的东西可以检索“username”中的值并允许我更改它


1条回答
网友
1楼 · 发布于 2024-04-25 00:39:31

您需要使用变量来存储Choice实例,设置用户名,然后调用Model.save()将其写入数据库

choice = Choice.objects.get(whatever criteria you use to get the instance)
choice.username = Users.objects.latest("name").username
choice.save()

相关问题 更多 >