我仍然是 Django 的初学者并正在构建一个管理系统,我希望使用来自 2 个表(GoCustomerRegisration 和 GoCustomerStatus)的 for 循环来显示数据库中的内容。但不幸的是,当我遍历一个表时,另一个表只给我带来了该表的最后一个元素。我真正想做的是一次遍历两个表,每个元素都应该在另一个表上对应它。在下面查看我的代码:
东西.html
{% for item in detail %}
<tr>
<td>
<a class="text-black text-decoration-none" href="{{ item.photo.url }}">
<img class="rounded-circle me-2" style="object-fit: contain; background-color:#91debb; border:1px solid palegreen;" alt="" width="30" height="30" src="{{ item.photo.url }}"></a>
</td>
<td>
<a class="text-black lg:hover:text-blue-400 text-decoration-none" href="{% url 'customer_detail' pk=item.id %}">{{ item.name }}</a>
</td>
<td class="text-capitalize">{{ item.type }}</td>
<td>{{ item.destination }}</td>
<td>{{ item.age }}</td>
<td>{{ item.time_of_submission }}</td>
<td>
<span>{{ hello.value }}%</span>
<div class="col">
<div class="progress progress-sm">
<div class="progress-bar progress-bar-striped bg-success" aria-valuenow="{{ hello.value }}" aria-valuemin="0" aria-valuemax="100" style="width: {{ h.value }}%;"><span class="visually-hidden"></span>
</div>
</div>
</div>
</td>
{% endfor %}
我的观点.py
@login_required
def preview(request):
global hello
detail = GoCustomerRegistration.objects.all()
next_event = Event.objects.last()
for i in range(1, (len(detail))+1):
print(i)
hello = GoCustomerStatus.objects.get(name_id=i)
print(hello)
context = {
'detail': detail,
'event': next_event,
'hello': hello,
}
return render(request, 'customers_preview.html', context)
我的 urls.py
from django.urls import path
urlpatterns = [
path('preview/', preview, name='preview'),
]
我的模型.py
class GoCustomerRegistration(models.Model):
name = models.CharField(max_length=300, verbose_name='Full name')
email = models.EmailField(null=False)
type = models.CharField(max_length=20, verbose_name='Customer Type')
destination = models.CharField(max_length=30, null=False, verbose_name='Destination')
time_of_submission = models.DateTimeField(auto_now_add=True, null=False, verbose_name=' Submit Time')
phone_number = models.IntegerField(verbose_name='Phone number')
age = models.IntegerField(verbose_name="Age", null=False)
photo = models.ImageField(max_length=10000, verbose_name='Customer Picture',
null=False, upload_to='customers/profiles/')
documents = models.FileField(upload_to='%Y/customers/documents/')
class Meta:
ordering = ["time_of_submission"]
verbose_name = "Customer Registration"
verbose_name_plural = "Customers Registration"
def __str__(self):
return self.name
class GoCustomerStatus(models.Model):
name = models.OneToOneField(GoCustomerRegistration,
max_length=300, verbose_name='Full name',
on_delete=models.CASCADE, primary_key=True,
null=False,
)
value = models.IntegerField(default=0, verbose_name='Level', null=False, primary_key=False)
class Meta:
verbose_name_plural = 'Customers Status'
verbose_name = 'Customer\'s Status'
def __str__(self):
return self.name.name