django 2-用户和用户配置文件模型,如何在单个查询中获取所有字段?

时间:2018-07-03 16:02:10

标签: python django python-3.6 django-2.0

下面的更新和解决方案。

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

我创建了一个配置文件模型,该模型通过在admin中工作的一对一字段链接到标准用户模型。我想将两个模型的所有字段/数据都拉到一个查询集中。我正在尝试创建一个用户编辑表单,我想基于当前登录的用户为“用户”和“个人资料”提取所有字段,并显示这些字段,我将使用页面来编辑和保存这些字段。

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

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 }}

1 个答案:

答案 0 :(得分:1)

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

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

相关问题