首页 > 解决方案 > 如何与父级一起显示多个相关的外键

问题描述

我尝试在模板中制作一个表格,第一行显示父母(习惯),下一行显示七个孩子(天)(外键)。使用 for 循环,我尝试重复该过程,但失败了。期望的结果应该是这样的,但在第 7 天后停止: 在此处输入图像描述 我需要一个 for 循环,因为我还不知道我必须显示多少习惯。

这是我的模型(为清楚起见而缩写):

class Habit(models.Model):
    habit_name = models.CharField(max_length=30)

class HabitTracking(models.Model):
    habit = models.ForeignKey(Habit, on_delete=models.CASCADE, 
            related_name="habit_day")
    habit_date = models.DateField()

我的观点:

from .models import Habit, HabitTracking

def habit_list(request):
    today = datetime.now().date()
    start_of_week = today - timedelta(days=today.weekday())
    end_of_week = start_of_week + timedelta(days=6)
    habits = Habit.objects.all().order_by('pk')
    next_7_days = HabitTracking.objects.order_by('habit__id', 
           'habit_date').filter(
            habit_date__gte=start_of_week
                ).filter(
            habit_date__lte=end_of_week)
    first_day = HabitTracking.objects.order_by('habit__id').filter(
            habit_date__gte=start_of_week
                ).filter(
            habit_date__lte=start_of_week + timedelta(days=6))

    return render(request, 'habit_tracker/habit_list.html',
        {
         'habits': habits, 
         'next_7_days': next_7_days,
         'today': today.strftime("%d.%m.%y"), 
         'start_of_week': start_of_week,
         'end_of_week': end_of_week, 'first_day': first_day
         })

这是我的模板:

   <table>
       <thead>
           <tr>
               <th>Habit</th>
               <th>S</th>
               <th>...</th>
           </tr>
       </thead>
       <tbody>
           {% for habit in habits %}
           <tr>
               <td>{{ habit.habit_name }}</td>
               {% for day in first_day %}
               <td>{{ day.habit_date|date:"d" }}</td>
               {% endfor %}
           </tr>
           {% endfor %}
       </tbody>
   </table>

谢谢你指引我正确的方向。

标签: djangotemplates

解决方案


我通过创建一个包含所有所需信息的嵌套 for 循环的字典并将其交给模板来解决我的问题:

视图.py

from datetime import datetime, timedelta
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.utils import timezone

from .models import Habit, HabitTracking

def habit_list(request):
    today = datetime.now().date()
    start_of_week = today - timedelta(days=today.weekday())
    end_of_week = start_of_week + timedelta(days=6)
    habits = Habit.objects.all().order_by('pk')
    habits_and_days = []
    for habit in habits:
        one_habit = {"habit": habit}
        next_7_days = HabitTracking.objects.order_by('habit__id', 'habit_date').filter(
                habit__pk=habit.id
                    ).filter(
                habit_date__gte=start_of_week
                    ).filter(
                habit_date__lte=end_of_week)
        for counter, day in enumerate(next_7_days, 1):
            days = {str(counter): day}
            one_habit.update(days)
        habits_and_days.append(one_habit)

    return render(request, 'habit_tracker/habit_list.html',
            {
                'today': today.strftime("%d.%m.%y"), 
                'start_of_week': start_of_week, 
                'end_of_week': end_of_week, 
                'habits_and_days': habits_and_days,
            })

habit_list.html

{% extends 'habit_tracker/base.html' %}

{% block habit_tracker_content %}
<div class="container">
    <div class="section">
        <h2 class="center blue-text text-darken-4">Habit Tracker</h2>
        </div>
        <div class="section">
            <p>Week from {{ start_of_week|date:"d.m.y" }} to {{ end_of_week|date:"d.m.y" }}</p>
            <p>Today: {{ today }}</p>
            <table>
                <thead>
                    <tr>
                        <th>Habit</th>
                        <th>S</th>
                        <th>M</th>
                        <th>T</th>
                        <th>W</th>
                        <th>T</th>
                        <th>F</th>
                        <th>S</th>
                    </tr>
                </thead>
                <tbody>
                    {% for habit in habits_and_days %}
                    <tr>
                        <td>{{ habit.habit.habit_name }}</td>
                        <td>{{ habit.1.habit_date|date:"d" }}</td>
                        <td>{{ habit.2.habit_date|date:"d" }}</td>
                        <td>{{ habit.3.habit_date|date:"d" }}</td>
                        <td>{{ habit.4.habit_date|date:"d" }}</td>
                        <td>{{ habit.5.habit_date|date:"d" }}</td>
                        <td>{{ habit.6.habit_date|date:"d" }}</td>
                        <td>{{ habit.7.habit_date|date:"d" }}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>
{% endblock %}

结果 在此处输入图像描述


推荐阅读