django 2 - User 和 userprofile 模型,如何在单个查询中获取所有字段?

django 2 - User and userprofile models, how to obtain all fields in a single query?

下面的更新和解决方案。

我一直在寻找解决方案,但没有找到任何突出的解决方案。

我创建了一个配置文件模型,该模型通过在管理员中运行的一对一字段链接到标准用户模型。我想将两个模型的所有 fields/data 拉到一个查询集中。我正在尝试创建一个用户编辑表单,我想根据当前登录的用户拉入用户和配置文件的所有字段并显示这些字段,我将有一个页面来编辑和保存这些字段。

实现此目的的最佳选择是什么,越简单越好。

class Profile(models.Model):
    address = models.blablabla
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')

def profile_edit(request):
    form = UserProfileForm(request.POST or None)
    instance = Profile.objects.all().filter(user__username=request.user).values # This is the place I need to create a single queryset.
    if request.method == "POST" and form.is_valid():
        form = UserProfileForm(request.POST, instance=instance)
        user_form = form.save()
        print("POST event")
    else:
        form = UserProfileForm(instance=instance)
        print(form)
    return render(request, 'frontend/profile_edit.html', {'form': form})

我在模板中手动创建表单,所以我想要类似 {{ form.username }} {{ form.profile.address }} 或类似的东西。我可能做得不好,我是 django 的新手。

更新 完整的解决方案

完成在代码和模板中访问用户和配置文件模型的步骤。

我决定不用我自己的模型替换用户模型,以防我错过了 django 提供的功能。它似乎也使以后可能会受到伤害的事情复杂化。所以我使用了单独的 UserProfile 模型并将其附加到 User 模型。这是我为未来的读者所做的。

models.py

from django.db.models.signals import post_save

class UserProfile(models.Model):
#take note of the related_name='profile' this is used to reference the fields in code and template.

#Each field of type 'text' I added default='' at the end, I got an error when it was int based so I removed the flag for that field.  I read this might cause an error when you try and auto-create the profile, see what works for you and you might not want it.

        user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') 
        country = models.CharField(max_length=2, blank=True, null=True, default='')
        ...

    # Auto-create the profile upon user account creation.  It's important to start with a fresh database so the user and profile ID's match.

        def create_user_profile(sender, instance, created, **kwargs):
            if created:
                UserProfile.objects.create(user=instance)

        post_save.connect(create_user_profile, sender=User)
    # Create your models here.

#In code, you can access your user and profile field data like so.

request.user.profile.fieldname
request.user.fieldname

In template you can do the same

{{ user.fieldname }}
{{ user.profile.fieldname }}

这里根本不需要查询 - 您不需要查询集,您需要单个实例。

在这种情况下,request.user.profile 将为您提供与当前用户相关的整个个人资料对象。