【发布时间】:2021-03-19 00:21:49
【问题描述】:
我在“models.py”文件中有两个模型类。 Signup & Notes
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
class Signup(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
contact = models.CharField(max_length=10, null=True)
branch = models.CharField(max_length=30)
campus = models.CharField(max_length=30)
role = models.CharField(max_length=15)
def __str__(self):
return self.user.username
class Notes(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
uploadingdate = models.CharField(max_length=30)
branch = models.CharField(max_length=30)
subject = models.CharField(max_length=30)
topic = models.CharField(max_length=200)
notesfile = models.FileField(null=True)
filetype = models.CharField(max_length=30)
description = models.CharField(max_length=300, null=True)
status = models.CharField(max_length=15)
def __str__(self):
return self.user.username + " " + self.status
在我的函数中,我使用 notes = Notes.objects.all() 和 users = User.objects.all() 来获取它们。
这里是函数
def indexnotes(request):
notes = Notes.objects.all()
users = User.objects.all()
d = {'notes' : notes,'users' : users}
return render(request,'indexnotes.html',d)
我正在使用 for 循环来显示数据表上的值。代码是这样的
<tbody >
{% for i in notes %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{i.user.first_name}} {{i.user.last_name}}</td>
<td>{{i.uploadingdate}}</td>
<td>{{i.campus}}</td>
<td>{{i.subject}}</td>
<td><a href="{{i.notesfile.url}}" class="btn btn-success" download>Download</a></td>
<td>{{i.filetype}}</td>
<td>{{i.description}}</td>
<td>{{i.status}}</td>
<td><a href="{% url 'assign_status' i.id %}" class="btn btn-success" >Assign Status</a></td>
<td><a href="{% url 'delete_notes' i.id %}" class="btn btn-danger" onclick="return confirm('Are you sure?')">Delete</a></td>
</tr>
{% endfor %}
</tbody>
现在问题是表的某些值来自 users 。由于 for 循环正在运行 notes .. 数据表不显示来自 users AKA Users 表的一些值。但我也想向他们展示。我试图合并 user 和 notes 但很遗憾没有成功。
我是 Django 新手。任何建议都会被采纳。 提前致谢。
【问题讨论】:
-
你的问题我不清楚;您是要在同一张表上显示
Users 和Notes,还是要从相应的Note中获取User属性? -
@etnguyen03 是的,你是对的。我想从对应的“Note”中获取所有“用户”属性,如“校园”、“角色”。
标签: python django django-models model django-forms