Django中使用外键搜索列表中的列表

huangapple go评论75阅读模式
英文:

Django search list in a list with foreign key

问题

我正在学习Django(也是编码),但有一件我认为非常简单的事情我做不出来。我想创建一个简单的项目管理应用。

我创建了两个模型:Project(项目)和Step(步骤)。在Step模型中,有一个外键关联到Project模型。

class Project(models.Model):
    title = models.CharField(max_length=100)

    def __str__(self):
        return self.title

class Step(models.Model):
    title = models.CharField(max_length=100)  
    project = models.ForeignKey('Project', on_delete=models.CASCADE, null=True)

我成功创建了一个项目的步骤,并能够列出一个项目的所有步骤,但现在在我的首页,我想列出所有的项目以及每个项目中的4个步骤,例如:

项目1(步骤1,步骤2,步骤3,步骤4)
项目2(步骤1,步骤2,步骤3,步骤4)

我正在使用ListView,但我不知道该怎么做,因为在我的步骤模型中有项目的ID。那么,我应该如何按项目排序步骤呢?

class ProjectList(ListView):
    model = Project 
    template_name = 'project/index.html'

我是否需要创建一个查询集?如果需要,我应该写什么?

queryset = Step.objects.filter(project_id='?')

我在思考,也许我在外键上做错了什么,也许我应该将任务(task)放在项目中。

希望你能理解我想要做的事情,谢谢你阅读我的问题 Django中使用外键搜索列表中的列表

英文:

i'm beginning in django (and coding too) and i can't do something which i guess is super easy . I want to create a simple project management .

I created 2 models : Project and Step . And in step there are a foreign key for 1 project.

class Project(models.Model):
title = models.CharField(max_length=100)

def __str__(self):
    return self.title

class Step(models.Model):
    title = models.CharField(max_length=100)  
    project= models.ForeignKey('Project', on_delete=models.CASCADE, null=True)

I succed to create a step in a project , to do a list to see all step for 1 project but now in my home page , i want to list all projects and 4 steps in each project for example :

Project 1 (Step 1, Step 2, Step 3 ,Step 4)
Project 2 (Step 1, Step 2, Step 3, Step 4)

I'm using the ListView , but i don't know what to do , because it's in my step there are the id of project . So how I sort steps by project ?

class ProjectList(ListView):
model = Project 
template_name ='project/index.html'

Do i need to create a queryset if so what i should write ?

queryset = setp.objects.filter(project_id='?')

I'm thinking maybe i did something wrong with the foreign key , and i maybe should put task in project .

I hope you understand what i want to do and thank you to read me Django中使用外键搜索列表中的列表

答案1

得分: 2

Sure, here is the translated code part:

{% for obj in object_list %}
   <h1>{{ obj.title }}</h1>
   {% for step in obj.step_set.all %}
      <p>{{ step.title }}</p>
   {% endfor %}
{% endfor %}

Please let me know if you need any further assistance.

英文:
{% for obj in object_list %}
   &lt;h1&gt;{{ obj.title }}&lt;/h1&gt;
   {% for step in obj.step_set.all %}
      &lt;p&gt;{{ step.title }}&lt;/p&gt;
   {% endfor %}
{% endfor %}

you can do this way in your templates.

huangapple
  • 本文由 发表于 2020年1月6日 15:10:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608021.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定