【问题标题】:How to retrieve data from relational database in Django如何从 Django 中的关系数据库中检索数据
【发布时间】:2020-06-09 21:40:12
【问题描述】:

此 Child_detail 模型与 Clinical_test 模型相关

class Child_detail(models.Model):
    Firstname = models.CharField(max_length = 50)
    Lastname = models.CharField(max_length = 50)
    Tribe = models.CharField(max_length = 50)
    Religion = models.CharField(max_length = 50)
    Date_of_birth = models.DateField()
    Current_Address = models.CharField(max_length = 50)


    def __str__(self):
        return self.Firstname

这是我想从中检索数据的临床测试模型

class Clinical_test(models.Model):
    child = models.ForeignKey(Child_detail, on_delete = models.CASCADE) 
    Test_type = MultiSelectField(max_length=100,choices=test_type,max_choices=30)
    Test_date = models.DateTimeField()
    Next_schedule_test_date = models.DateField(blank=True)

    def __str__(self):
        return str(self.Test_type)

这是我的观点.py

def more_about_child(request,pk):
    child = get_object_or_404(Child_detail,pk=pk)
    context={
        'child':child,        
    }
    return render(request,'functionality/more.html',context)

这是我的 template.html,用于显示检索到的数据

<div class="container" style="margin-top:20px">
    <div class="col-md-12" style="background-color:rgb(44, 44, 3);color:white">
        <h4>clinical test</h4>
    </div>
    <div class="row">
        <div class="col-md-3">
            <p>First name: <b>{{clinical.child.Test_date}}</b> </p>
        </div>
        <div class="col-md-3">
            <p>Last name: <b>{{child.Lastname}}</b> </p>
        </div>
        <div class="col-md-3">
            <p>Tribe: <b>{{child.Tribe}}</b> </p>
        </div>
        <div class="col-md-3">
            <p>Religion: <b>{{child.Religion}}</b> </p>
        </div>
        <div class="col-md-3">
            <p>Religion: <b>{{child.Date_of_birth}}</b> </p>
        </div>
        <div class="col-md-3">
            <p>Religion: <b>{{child.Current_Address}}</b> </p>
        </div>
    </div>
</div>

【问题讨论】:

    标签: django orm model relational-database


    【解决方案1】:

    这是一步一步的解决方案-(据我了解您需要什么)

    1. 首先使用 pk 从 Child 详细信息类中查询子项

      child_detail = Child_detail.objects.get(pk=pk)

    2. 现在,从 Clinical_test 查询

      child = Clinical_test.objects.filter(Child_detail=child_detail)

    之后,您可以将child 发送到上下文。

    【讨论】:

    • 我已经将孩子传递给上下文,但我很难将数据渲染到模板中,请帮助
    • 所以,您在渲染数据时遇到了问题。首先,通过 print(child) 确认您传递的信息是正确的。
    猜你喜欢
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多