从我的Django模型获取所有用户的问题

2024-06-28 10:54:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让所有的用户从我的数据库显示所有的用户名,目标和目标id使用相关的名称,但我似乎不能这样做

型号

class GoalStatus(models.Model):
    status_name = models.CharField(max_length=60)

    def __str__(self):
        return self.status_name



class ScrumyGoals(models.Model):
    goal_status = models.ForeignKey(GoalStatus, on_delete=models.PROTECT, related_name='goalstatus')
    user = models.ForeignKey(User, related_name='scrumygoals', on_delete=models.PROTECT)
    goal_name = models.CharField(max_length=60)
    goal_id = models.IntegerField()
    created_by = models.CharField(max_length=60)
    moved_by = models.CharField(max_length=60)
    owner = models.CharField(max_length=60)

查看

def home(request):
    user = User.objects.all()
  #  User1 = ScrumyGoals.objects.filter(goal_name='Learn Django')


    context = {'User': User}
    return render(request, 'django/home.html', context)

模板

{% for g in User.scrumygoals_set.all %}
        <td>g.User.User</td>>
        <td>g.goal_name</td>>
        <td>g.goal_id</td>>


    {% endfor %}

输出应该是这样的

User      Weekly Goals     Daily Goals     Verify Goals    Done Goals
username    Goalname Goalid Goalname Goalid

Tags: nameid目标modelmodelsstatuslengthmax
1条回答
网友
1楼 · 发布于 2024-06-28 10:54:13

不能以这种方式在模板中进行查询。试试这个:

视图.py

def home(request):
    users = User.objects.all()
    context = {'users': users}
    return render(request, 'django/home.html', context)

django/主页.html

{% for g in users %}
    <td>{{ g.username }}</td>>
    <td>{{ g.scrumygoals.goal_name }}</td>>
    <td>{{ g.scrumygoals.goal_id }}</td>>
{% endfor %}

或者,如果您希望在ScrumyGoal实例之间循环,请执行以下操作:

视图.py

def home(request):
    scrumy_goals = ScrumyGoals.objects.all()
    context = {'scrumy_goals': scrumy_goals}
    return render(request, 'django/home.html', context)

django/主页.html

{% for g in scrumy_goals %}
    <td>{{ g.user.username }}</td>>
    <td>{{ g.goal_name }}</td>>
    <td>{{ g.goal_id }}</td>>
{% endfor %}

相关问题 更多 >