从 Django 数据库中获取数据

Get data from django database

那么,如何从 Django 数据库获取数据?我有 Django 模型并创建了 2 个对象 there.I 想要获取 2 个对象并写入 html 文件。管理面板:https://i.stack.imgur.com/7WUZr.png

view.py

    def vds(request):
    HTML_STRING = render_to_string("vds.html", context=context1)
    return HttpResponse(HTML_STRING)
VDSTARIFS_obj = VDSTARIFS.objects.get(id=1)
context1 = {
    "prise": VDSTARIFS_obj.prise,
}

模型文件

class VDSTARIFS( models.Model):
    prise = models.CharField(max_length= 10,)
    
    def __str__(self):
        return str(self.prise)```

参考 Django 文档:

https://docs.djangoproject.com/en/3.2/intro/tutorial03/#a-shortcut-render

from django.shortcuts import render
from .models import Question

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)

已为您的模型编辑

from django.shortcuts import render
from .models import VDSTARIFS

def vds(request):
    ALL_VDSTARIFS = VDSTARIFS.objects.all()
    FIRST_VDSTARIF = ALL_VDSTARIFS[:1]

    # Get prise
    prise = FIRST_VDSTARIF.prise

    # Alternatives to print 'prise' in template 

    # Pass only the first item of vds list
    context = {
        "FIRST_VDSTARIF": FIRST_VDSTARIF
    }

    # Pass prise only
    
    context = {
        "prise": prise
    }

    # All records in html also the needed one in separated item
    context = {
        "ALL_VDSTARIFS": VDSTARIFS,
        "FIRST_VDSTARIF": FIRST_VDSTARIF
    }

    return render(request, 'vds.html', context)
}

在模板中你可以使用 if https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#if

{# Runs along all tarifs and print only one, not good. #}
{% for vdstarif in ALL_VDSTARIFS %}
 {% if vdstarifs.id == "1" %}
   {{ vdstarif.prise }}
 {% endif %}
{% endfor %}

{# Only print the needed one #}
{{ FIRST_VDSTARIF.prise }}


{# Print prise #}
{{ prise }}

您可能会遵循 python 和 django 编码约定以及我的建议。

重命名 VDSTARIFS -> VdsTarif(查看您的管理页面,Django 将 's' 添加到您的模型以使其成为复数)

为您的模型使用单数名称并为视图中的变量名称添加后缀,例如 vdstarif_list。

对于“prise”字段使用 DecimalField,看起来它是一个 CharField。是奖品还是价格? https://docs.djangoproject.com/en/3.2/ref/models/fields/#decimalfield

from django.shortcuts import render
from .models import VdsTarif

def vds(request):
   vdstarif_list = VdsTarif.objects.all()

   context = {
        "vdstarif_list" : vfstarif_list[:0].prise
   }

   return render(request, 'vds.html', context)