从相关的UserProfile模型访问字段

时间:2016-02-01 10:02:18

标签: python django django-models

我在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)

我能够显示email模块中的User,但我真正希望展示的是来自UserProfile的数据。

请,任何建议。

谢谢。

2 个答案:

答案 0 :(得分:1)

而不是使用

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

答案 1 :(得分:0)

使用OneToOneField

要使其更加直接,我会使UserProfileOneToOneField建立User关系,而不是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,一组你必须过滤/索引才能选择。