如何在Django模板嵌入式模型中显示?

时间:2018-10-26 23:56:19

标签: django mongodb django-models django-templates djongo

models.py

class Decomposicao(models.Model):    
    tirosina = models.BooleanField('tirosina')
    fenilalanina = models.BooleanField('fenilalanina')
    class Meta:
        abstract = True


class SDF(models.Model):
    numero = models.IntegerField('SDF', unique=True, primary_key=True)

    decomposicao = models.EmbeddedModelField(
        model_container=Decomposicao,
    )

    data_insercao = models.DateTimeField(auto_now_add=True)

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

views.py

def search(request):
    data = {}
    if request.method == 'GET':
        search = request.GET
        search = search['sdf']
        if search.startswith("SDF") or search.startswith("sdf"):
            sdf = SDF.objects.get(pk=search[3:])            
        else: 
            sdf = SDF.objects.get(pk=search)
    data['sdf'] = sdf
    data['numero'] = format(sdf.numero, '04d')
    return render(request, 'app/busca.html', data)

我正在使用mongodb和django,所以我决定将djongo用作连接器-djongo doc-据说我正在尝试显示在django模板中的查询中找到的内容-busca.html-但我找不到显示嵌入式模型的方法。

busca.html

{% extends 'app/base.html' %}

{% block cabecalho %}
{% load staticfiles %}
<title>SDF{{ numero }}</title>
{% endblock%}

{% block conteudo %}

<section class="bg-light">
<div class="container ">
    <div class="col-lg-12 h-100 text-center text-lg-left my-auto">
        <h1 class="text-muted medium mb-4 mb-lg-0">SDF{{ numero }</h1>
        <br>
        {{ sdf }}
    </div>
</div>
</section>
{% endblock %}

这样做只会显示sdf的数字-“ numero”。

谢谢。

1 个答案:

答案 0 :(得分:0)

{{ sdf }}调用模型的__str__方法,该方法返回定义的numero。要显示所有字段,请使用{{ sdf.numero }}{{ sdf.decomposicao }}{{ sdf.data_insercao }}。我相信您可以使用点符号来访问嵌入式模型的字段,例如{{ sdf.decomposicao.tirosina }}