首页 > 解决方案 > 如何对 django 模型执行下一个查询

问题描述

所以我有这两个模型

  1. 配置文件(与我的默认 django 用户模型具有一对一的关系)
  2. Item 模型(也与我的默认 django User 模型具有一对一的关系)来自 Item 模型,我如何使用 User 模型访问 Profile 模型

请在下面查看我的代码

我的模特

class Profile(models.Model):
   user = models.OneToOneField(User, on_delete=models.CASCADE)
   phone = models.CharField(max_length=200,null=True) ```

My View

def home(request):
   all_item_lists = Item.objects.all()

   context = {
       'all_item_lists':all_item_lists
       }
   return render(request, 'findit/home.html', context)

My Template

{% for list in all_item_lists %}
      <!-- how want to get the phone number of the user that posted this Item -->  
                       <span>{{list.owner.first_name }}</span>                                     
                 {% endfor %}```

标签: djangodjango-modelsdjango-viewsdjango-templatesdjango-related-manager

解决方案


您可以使用以下方式访问用户的个人资料user.profile

{% for list in all_item_lists %}
    <span>{{ list.owner.profile.phone }}</span>
    <span>{{ list.owner.first_name }}</span>
{% endfor %}

推荐阅读