Django 自从删除getProfile()后,如何从用户配置文件中查询数据?
我的理解是,自从Django 1.5以来,定制用户模型是可能的,但不是必需的。事实上,Greenfeld和Roy在“两勺Django”一书中指出,有时候(比如创建第三方软件包)“Profile”模型仍然是一条路要走。 然而,由于getProfile()已被删除,我不知道如何将模板中的配置文件数据作为目标。因为:Django 自从删除getProfile()后,如何从用户配置文件中查询数据?,django,django-models,Django,Django Models,我的理解是,自从Django 1.5以来,定制用户模型是可能的,但不是必需的。事实上,Greenfeld和Roy在“两勺Django”一书中指出,有时候(比如创建第三方软件包)“Profile”模型仍然是一条路要走。 然而,由于getProfile()已被删除,我不知道如何将模板中的配置文件数据作为目标。因为: {{ request.user.get_profile.id }} 不再生成任何数据,我已尝试: {{ request.user.userprofile.id }} 但这也不会产生价
{{ request.user.get_profile.id }}
不再生成任何数据,我已尝试:
{{ request.user.userprofile.id }}
但这也不会产生价值
所以我的问题是,考虑到以下模型:
class UserProfile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, unique=True, null=True, on_delete=models.SET_NULL)
fullname = models.CharField(max_length=64, unique=False)
company = models.ForeignKey(ClientList, blank=False, null=True, db_column='client', on_delete=models.SET_NULL)
position = models.CharField(max_length=64, unique=False, blank=True, null=True)
egroup = models.CharField(max_length=50, choices=EMP_GROUP_CHOICES)
address1 = models.CharField(max_length=130, unique=False, blank=True, null=True)
address2 = models.CharField(max_length=30, unique=False, blank=True, null=True)
city = models.CharField(max_length=64, unique=False, blank=True, null=True)
state = models.CharField(max_length=64, unique=False, blank=True, null=True)
zipcode = models.CharField(max_length=15, unique=False, blank=True, null=True)
phone = models.CharField(max_length=15, unique=False, blank=True, null=True)
extension = models.CharField(max_length=15, unique=False, blank=True, null=True)
hphone = models.CharField(max_length=15, unique=False, blank=True, null=True)
mobile = models.CharField(max_length=15, unique=False, blank=True, null=True)
fax = models.CharField(max_length=15, unique=False, blank=True, null=True)
notes = models.TextField(max_length=2000, blank=True, null=True)
email = models.EmailField()
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
def __str__(self):
return u'%s' % self.fullname
class Meta:
ordering = ['fullname']
class Admin:
pass
如何在模板中获取userprofile.id
(注意:并非真正相关,但用户对象仍明确使用外键以保留“on_delete”参数)要存储用户配置文件,建议使用
OneToOneField
而不是ForeignKey
和unique=True
。尽管它们是等价的
将关系设置为OneToOneField
后,可以使用以下查询检索userprofile id:user.userprofile.id
如果您决定将ForeignKey
与unique=True
一起使用,您仍然可以使用以下查询集检索它:user.userprofile\u set.first()
参考:first()
queryset在Django 1.6及更高版本中介绍。对于Django 1.5及以下版本,请使用以下查询:user.userprofile\u set.all()[0]