Django数据库查询集无字段信息

时间:2018-06-25 21:26:58

标签: django django-models django-database

当我通过视图运行查询集并将其传递给模板时,我得到的是以下内容:

import './style.css';
screenLog.init()

import { from } from 'rxjs/observable/from';
import { of } from 'rxjs/observable/of';
import { race } from 'rxjs/observable/race';
import { timer } from 'rxjs/observable/timer';
import { groupBy, mergeMap, toArray, map, reduce, concatMap, delay, concat, timeout, catchError, take } from 'rxjs/operators';

// simulate a element that appear at t0, then at t30s, then at t10s
const obs1$ = of('aa ');
const obs2$ = of('bb ').pipe(delay(3000));
const obs3$ = of('cc ').pipe(delay(10000));


const example2 = obs1$.pipe(concat(obs2$.pipe(concat(obs3$))), timeout(4000), catchError(a => of('timeout'))); // here in the catchError, execute your function

const subscribe = example2.subscribe(val => console.log(val + ' ' + new Date().toLocaleTimeString())); 

如何通过查询显示字段字典?

views方法:

<QuerySet [<ChangeLog: ChangeLog object (1)>, <ChangeLog: ChangeLog object (2)>, <ChangeLog: ChangeLog object (3)>, <ChangeLog: ChangeLog object (4)>, <ChangeLog: ChangeLog object (5)>, <ChangeLog: ChangeLog object (6)>, <ChangeLog: ChangeLog object (7)>, <ChangeLog: ChangeLog object (8)>, <ChangeLog: ChangeLog object (9)>, <ChangeLog: ChangeLog object (10)>, <ChangeLog: ChangeLog object (11)>]

模板:

def changeres(request):
    if request.user.is_authenticated:
            name = request.session.get('name')
            data = ChangeLog.objects.all()
            return render(request, 'changeres.html', {'data':  data})

{{data}}只是作为概念证明,直到我可以使其正常工作为止

1 个答案:

答案 0 :(得分:1)

  1. 您无法直接显示查询集,需要在模板中对其进行迭代。
  2. 您可以使用object.myfieldname访问模板中对象的字段。

示例:

{% for item in data %}
   <p>item.one_of_my_fields</p>
{% endfor %}

您还可以为您的类定义默认的字符串方法,因为您可以看到django默认返回ChangeLog object (1)

示例:

class Genre(models.Model):

    name = models.CharField(max_length=30, unique=True)

    def __str__(self):
        return self.name

现在,我可以直接在模板中调用对象,它将返回流派的名称。

{% for item in data %}
    <p>item</p>
{% endfor %}