django - 如何对 django 模型执行下一个查询
问题描述
所以我有这两个模型
- 配置文件(与我的默认 django 用户模型具有一对一的关系)
- 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 %}```
解决方案
您可以使用以下方式访问用户的个人资料user.profile
{% for list in all_item_lists %}
<span>{{ list.owner.profile.phone }}</span>
<span>{{ list.owner.first_name }}</span>
{% endfor %}
推荐阅读
- vhdl - 在 MAX10 FPGA 上使用 PLL 产生优于 400Mhz 的时钟信号
- c++ - 调用 Windows 挂钩时,运行哪个代码?
- python - 在二进制数组中强制最小间隔
- reactjs - 如果我有这三行,如何将功能组件转换为类组件?
- javascript - 如何使用 Redux 和 React 从数据库中获取单个数据元素?
- c++ - 具有 STL 向量的复制构造函数与赋值运算符
- html - 在绝对定位的 div 内定位绝对定位的表单
- macos - 第三方应用程序快捷方式所需的 Alt 键
- xamarin.forms - 如何使用 Xamarin.Essentials Launcher 将 Android 设置应用程序启动到您的应用程序设置?
- python - 将数据重采样为每周数据?