gpt4 book ai didi

django - 如何在Django中从一对多关系中检索数据?

转载 作者:行者123 更新时间:2023-12-01 12:26:10 25 4
gpt4 key购买 nike

我正在使用Django 1.10创建我的个人网站

这是技能应用程序的模型:

from __future__ import unicode_literals

from django.db import models


# Create your models here.
class Skill(models.Model):
name = models.CharField(max_length=256)
created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True, auto_now_add=False)

def __unicode__(self):
return self.name

def __str__(self):
return self.name


class Subskill(models.Model):
skill = models.ForeignKey(Skill, on_delete=models.CASCADE)
name = models.CharField(max_length=256)
link = models.CharField(max_length=256)
created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True, auto_now_add=False)

def __unicode__(self):
return self.name

def __str__(self):
return self.name

并查看:
from django.shortcuts import render
from skill.models import Skill,Subskill


# Create your views here.
def home(request):
skill = Skill.objects.all()
subskill =Subskill.objects.all()
context = {'skills':skill,
'subskills':subskill}
return render(request, 'skill.html', context)

这是我的模板页面:

skill.html
{% block skill %}
{% for subskill in subskills %}
{{subskill.skill.name}}
{{subskill.name}}
{% endfor %}
{% endblock skill %}

假设有一个名为web design的技能,它具有两个名为html和css的子技能。
我想像技能名称一样在 View 页面中进行渲染,这是两个 child 的名字:

网页设计

Html

的CSS

但它呈现的就像Web设计HTML Web设计CSS一样

请帮我解决这个问题。

最佳答案

您可以对技能本身进行realted query
https://docs.djangoproject.com/en/1.10/topics/db/queries/#backwards-related-objects

# example
skill_obj = Skill.objects.all()[0]
subskills = skill_obj.subskill_set.all()

还是你的情况
def home(request):        
skills = Skill.objects.all().prefetch_related('subskill_set') # optimizing
context = {'skills':skills}
return render(request, 'skill.html', context)

在模板中
{% for skill in skills %}
{{skill.name}}
{% for subskill in skill.subskill_set.all %}
{{subskill.name}}
{% endfor %}
{% endfor %}

关于django - 如何在Django中从一对多关系中检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39327418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com