相关UserProfile mod的访问字段

2024-06-01 12:21:16 发布

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

我在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的数据。你知道吗

拜托,有什么建议吗。你知道吗

谢谢你。你知道吗


Tags: 数据pyselfdatereturnmodelsdeflength
2条回答

使用OneToOneField

为了使它更直接,我将使UserProfileUser具有OneToOneField关系,而不是ForeignKey。因为这意味着一个给定的用户只能有一个配置文件。你知道吗

class Location(models.Model):
    user = models.OneToOneField(User)

在这种情况下,您可以使用location.user.userprofile.your_field更轻松地访问它

使用自定义MyUser模型

如果您想让这更直接,您可以创建一个自定义的MyUser模型,该模型将包含来自UserUserProfile的字段。你知道吗

大致是这样的:

from django.contrib.auth.models import AbstractBaseUser
class MyUser(AbstractBaseUser):
    # Adding your custom fields
    user_base = models.CharField(max_length=120, choices=LOCATION_CHOICES)
    user_position = models.CharField(max_length=120)
    user_phone = models.CharField(max_length=120)
    slug = models.SlugField()

class Location(models.Model)
    user = OneToOneField(MyUser) # Using your custom MyUser model

这允许更直接的访问,例如location.user.user_phone而不是location.user.userprofile.user_phone

我只提供了伪代码,请参考Django documentation

使用ForeignKey意味着您可能有多个配置文件

在另一种情况下,如果一个用户可能有多个用户配置文件,那么您就有了选择要使用哪个配置文件来提取相关数据的负担,因为这样关系将是user.userprofile_set,一个您必须过滤/索引才能选择的集。你知道吗

而不是使用

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 ^{} model,这样你就可以摆脱UserProfile。你知道吗


奖励提示:PositiveIntegerField不是电话号码的正确字段。前导零有意义。而且,PositiveIntegerField有一个最大值。改用CharField。你知道吗

相关问题 更多 >