简体   繁体   English

从Django模型返回多个字段

[英]Returning more than one field from Django model

How would one go about returning more than one field from a Django model declaration? 如何从Django模型声明中返回多个字段?

For instance: I have defined: 例如:我定义了:

class C_I(models.Model):
    c_id = models.CharField('c_id', max_length=12)
    name = models.CharField('name', max_length=100)
    def __str__(self):
        return '%s' % (self.name)

which I can use, when called in a views.py function to return 当在views.py函数中调用时,我可以使用它返回

    {{ c_index }}

        {% for c in c_index %}

            <div class='c-index-item' c-id=''>

                <p>{{ c.name }}</p>

            </div>

        {% endfor %}

from a template. 从模板。 This is being called in my views.py like so: 这在我的views.py中被调用,如下所示:

c_index = C_I.objects.all()

t = get_template('index.html')

c  = Context({'c_index': c_index})

html = t.render(c)

How would I also include the c_id defined in the model above, so that I can include {{c.name}} and {{c.c_id}} in my template? 我还要如何在上面的模型中包含定义的c_id,以便可以在模板中包含{{c.name}}和{{c.c_id}}? When I remove the str method, I appear to get all of the results, however, it just returns blank entries in the template and will not let me reference the individual components of the object. 当我删除str方法时,似乎可以得到所有结果,但是,它仅在模板中返回空白条目,而不会让我引用该对象的各个组件。

What you have is fine. 你所拥有的一切都很好。 Your template should be: 您的模板应为:

    {% for c in c_index %}
        <div class='c-index-item' c-id='{{ c.c_id }}'>
            <p>{{ c.name }}</p>
        </div>
    {% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM