代码之家  ›  专栏  ›  技术社区  ›  stanley oguazu

如何在django 2模板中查询主键对象

  •  0
  • stanley oguazu  · 技术社区  · 7 年前

    查询数据库后,我的模板不会显示任何内容。请查找随附的我的模型、url、模板

    模型

       class ScrumyUser(models.Model):
       userRole = (
           ('O', 'Owner'),
           ('A', 'Admin'),
           ('Q', 'Quality Analyst'),
           ('D', 'Developer'),
       )
       fullname = models.CharField(max_length=100)
       role = models.CharField(max_length=1, choices=userRole)
    
    
    
    class GoalStatus(models.Model):
       goalStatus = (
           ('P', 'Pending'),
           ('V', 'Verified'),
           ('D', 'Done'),
       )
       status = models.CharField(max_length=1, choices=goalStatus)
    
    
    class ScrumyGoals(models.Model):
       goalType = (
           ('WG', 'Weekly Goal'),
           ('DT', 'Daily Task'),
       )
    
       user_id = models.ForeignKey(ScrumyUser, on_delete=models.CASCADE)
       status_id = models.ForeignKey(GoalStatus, on_delete=models.CASCADE)
       goal_type = models.CharField(max_length=2, choices=goalType)
       goal_description = models.TextField()
       date_created = models.DateTimeField('dateCreated')
       date_updated = models.DateTimeField(null=True, blank=True)
    

    视图

    from django.views import generic
    from .models import ScrumyGoals, ScrumyUser, GoalStatus
    
    
    class IndexView(generic.ListView):
        template_name = 'greyscrumy/index.html'
        context_object_name = 'goals'
    
    
        def get_queryset(self):
    
            return ScrumyGoals.objects.all()
    

    模板索引

    此模板在浏览器上不显示任何数据

    {% if goals %} 
       <h1>{{ object_list.fullname }}</h1> 
       <ul>
       {% for goal in goals.scrumygoals_set.all %}
            <li><a href="{% url 'greyscrumy:index' goal.id %}">{{ goal.goal_type }}</a></li>
        {% endfor %}
        </ul>
    {% else %}
        <p>No goals are available.</p>
    {% endif %} 
    

    第二个显示,但我不知道如何访问SCRUMYUSER和GOALSTATUS

    请我真的很想了解这一点,我从昨天开始就在谷歌上搜索,但什么都找不到

    {% for goal in goals %}
    
        {% for innergoal in goals %}
            {{ innergoal.id }} {{ innergoal.goal_description }}
        {% endfor %}
    
    {% endfor %}
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   amirr    7 年前

    像这样:

    {% for goal in goals %}
        <h1>{{ goal.user_id.fullname }}</h1>
        <p>{{ goal.goal_type }}</p>
        <p>{{ goal.goal_description }}</p>
        <p>{{ goal.date_created }}</p>
        <p>{{ goal.date_updated }}</p>
        <p>{{ goal.user_id.role }}</p>
        <p>{{ goal.status_id.status }}</p>
    {% endfor %}