gpt4 book ai didi

python - 从相关 UserProfile 模型访问字段

转载 作者:太空宇宙 更新时间:2023-11-03 16:59:20 24 4
gpt4 key购买 nike

我在 Django 中选择数据时遇到一些问题。

models.py

class Location(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
my_location = models.CharField(max_length=120, choices=LOCATION_CHOICES)
update_date = models.DateField(auto_now=True, null=True)
date = models.DateField()


def __str__(self):
return self.my_location

class UserProfile(models.Model):
user = models.ForeignKey(User)
user_base = models.CharField(max_length=120, choices=LOCATION_CHOICES)
user_position = models.CharField(max_length=120)
user_phone = models.PositiveIntegerField()
slug = models.SlugField()

def save(self, *args, **kwargs):
self.slug = slugify(self.user)
super(UserProfile, self).save(*args, **kwargs)

def __unicode__(self):
return self.user.username

views.py

def index(request):
locations = Location.objects.order_by('-update_date')
context = {'locations': locations}
return render(request, 'index.html', context)

我能够显示来自 User 模块的电子邮件,但我真正想显示的是来自 UserProfile 的数据。

请给点建议。

谢谢。

最佳答案

而不是使用

user = models.ForeignKey(User)

用途:

user = models.OneToOneField(User)

One-to-one relationships更适合您的情况。如果您使用它们,您的 User 模型将自动获取一个 userprofile 属性,您可以像这样使用:

>>> user = User.objects.get(...)
>>> user.userprofile.user_phone
12345

您也可以考虑writing a custom User model ,这样您就可以摆脱UserProfile

<小时/>

额外提示: PositiveIntegerField 不是电话号码的正确字段。前导零是有意义的。此外,PositiveIntegerField 有一个最大值。请改用 CharField

关于python - 从相关 UserProfile 模型访问字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35127639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com