我在Django选择数据时遇到了一些问题。你知道吗
型号.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
视图.py
def index(request):
locations = Location.objects.order_by('-update_date')
context = {'locations': locations}
return render(request, 'index.html', context)
我能够显示来自User
模块的email
,但我真正想显示的是来自UserProfile
的数据。你知道吗
拜托,有什么建议吗。你知道吗
谢谢你。你知道吗
使用OneToOneField
为了使它更直接,我将使
UserProfile
与User
具有OneToOneField
关系,而不是ForeignKey
。因为这意味着一个给定的用户只能有一个配置文件。你知道吗在这种情况下,您可以使用
location.user.userprofile.your_field
更轻松地访问它使用自定义MyUser模型
如果您想让这更直接,您可以创建一个自定义的
MyUser
模型,该模型将包含来自User
和UserProfile
的字段。你知道吗大致是这样的:
这允许更直接的访问,例如
location.user.user_phone
而不是location.user.userprofile.user_phone
我只提供了伪代码,请参考Django documentation
使用ForeignKey意味着您可能有多个配置文件
在另一种情况下,如果一个用户可能有多个用户配置文件,那么您就有了选择要使用哪个配置文件来提取相关数据的负担,因为这样关系将是
user.userprofile_set
,一个您必须过滤/索引才能选择的集。你知道吗而不是使用
用途:
One-to-one relationships更适合你的情况。如果使用它们,
User
模型将自动获得一个userprofile
属性,您可以这样使用:你也可以考虑writing a custom ^{} model ,这样你就可以摆脱
UserProfile
。你知道吗奖励提示:
PositiveIntegerField
不是电话号码的正确字段。前导零有意义。而且,PositiveIntegerField
有一个最大值。改用CharField
。你知道吗相关问题 更多 >
编程相关推荐