我在大约一个月前开始使用Django,我遇到了问题。
我创建了一个与用户模型一对一链接的模型
这是我的models.py
文件:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class UserInfo(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
options = (('individual','Individual'),
('institute',"An institute"),
)
userAs = models.CharField(max_length=100,choices=options)
def __str__(self):
return self.user.username
class Meta:
ordering = ["user"]
@receiver(post_save,sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserInfo.objects.create(user=instance)
...我想从shell更改userAs
的值,我无法做到。
这就是我的尝试:
In [10]: us = User.objects.get(username="foo")
In [11]: us.userinfo.userAs
Out[11]: 'individual'
In [12]: type(us.userinfo.userAs)
Out[12]: str
In [13]: us.userinfo.userAs = 'institute'
In [14]: us.save()
In [15]: us.userinfo.userAs
Out[15]: 'institute'
In [16]: us = User.objects.get(username="steve04")
In [17]: us.userinfo.userAs
Out[17]: 'individual'
...但我无法改变它。
答案 0 :(得分:2)
您正在修改us.userinfo
并保存us
个实例。但是,us
没有变化。您修改了userinfo
内的us
对象,但未修改us
内的对象。
您应该保存us.userinfo
而不是us
,这是一个演示:
In [1]: us = User.objects.get(username="foo")
In [2]: us.userinfo.userAs = 'institute'
In [3]: us.userinfo.save()
In [4]: us = User.objects.get(username="steve04")
In [5]: us.userinfo.userAs
Out[5]: 'institute'