在Django中打印对象 [英] Printing Objects in Django

查看:282
本文介绍了在Django中打印对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我已经成功地将Django连接到预先存在的数据库(检查,验证和同步),并且创建了一个应用程序和一个项目以及所有这些内容(我正在阅读Django的书,并且在本章中5),但是当我实际运行它并打印内容时,出现了一个(假定的)错误。在python中时,我正确地导入了我需要的内容(从myapp.models import Artist 中的),但是,例如,如果我尝试打印表中的前五行( print Artist.objects.all()[:5] ),我得到了:

So I've connected Django to a pre-existing database successfully (inspect, validate and sync) and I've created an app and a project and all that (I'm reading the Django book and I'm on chapter 5), but when I actually run it and print stuff, I get an (assumed) error. While in python, I properly import what I need (from myapp.models import Artist) but if I try to print, for example, the first five rows in the table (print Artist.objects.all()[:5]), I get this:

[<Artist: Artist object>, <Artist: Artist object>, <Artist: Artist object>, <Artist: Artist object>, <Artist: Artist object>]

为什么它实际上不打印值,而不是显示占位符?

Why doesn't it actually print the values instead of what seems to be a placeholder? Is there something I'm missing here?

推荐答案

Django使用ORM(对象关系映射器)来回转换数据在Python对象和数据库行之间。因此,当您使用它从数据库中获取项目时,它会将其转换为Python对象。

Django uses an ORM (Object-Relational Mapper) that translates data back and forth between Python objects and database rows. So when you use it to get an item from the database, it converts it into a Python object.

如果该对象未定义如何将自身显示为文本, Django为您做到了。 Python做同样的事情:

If that object doesn't define how to display itself as text, Django does it for you. Python does the same thing:

>>> class MyObject(object):
...     pass
... 
>>> [MyObject(), MyObject()]
[<__main__.MyObject object at 0x0480E650>,
 <__main__.MyObject object at 0x0480E350>]






如果要查看每个对象行的所有实际值,请使用

以下是文档中的示例:

# This list contains a Blog object.
>>> Blog.objects.filter(name__startswith='Beatles')
[<Blog: Beatles Blog>]

# This list contains a dictionary.
>>> Blog.objects.filter(name__startswith='Beatles').values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]

这篇关于在Django中打印对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆