发新话题
打印

django翻译的Database API reference 部分

django翻译的Database API reference 部分

因工作需要,所以要看看Database API reference 部分这部分知识,苦于没有中文,所以只能看鸟文的,现在贴出来一部分,方便自己,也方便别人好多的地方翻译的还不太成熟,一些专业术语自己也忘的差不多了,有错大家请指来,谢谢!也算为中国开源做点儿贡献,以下是零散的一些,有空把纸面的东西整理好,再发上来吧! 转时请注明是www.dophp.net首发就OK了,有错请指来,我想要的不只是一个顶字,谢谢

Database API reference 部分

distinct()
Returns a new QuerySet that uses SELECT DISTINCT in its SQL query. This eliminates duplicate rows from the query results.
消除重复的查询结果
By default, a QuerySet will not eliminate duplicate
在默认的情况下不并消除重复的行
rows. In practice,在特殊的情下这个的确是个问题
this is rarely a problem, because simple queries such as Blog.
在blog 的应用中常用到
objects.all() don’t introduce the possibility of duplicate result rows.
Objects.all()并不能引入重复的数据行
However, if your query spans multiple tables,但是如是你的查询是合并多个表 it’s possible to get duplicate results when a QuerySet is evaluated.
结果集会检测到重复的数据是有可能性的 That’s when you’d use distinct().当你用distinct()时
values(*fields)
Returns a ValuesQuerySet — a QuerySet that evaluates to a list of dictionaries instead of model-instance objects.
返回一个QuerySet 经过计算过的字典列表而不是模型--对象实例
Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.
这些字典每一个代表着一个对象,相应的每个模型对象的属性名对应着一个Key
This example compares the dictionaries of values() with the normal model objects:这是一个用字典的value()和普通MODEL比较的例子
# This list contains a Blog object.此列表包含一个BLOG的对象
>>> Blog.objects.filter(name__startswith='Beatles')
[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.'}]
values() takes optional positional arguments,
value()带有可选参数
*fields, which specify field names to which the SELECT should be limited. If you specify the fields, each dictionary will contain only the field keys/values for the fields you specify. If you don’t specify the fields, each dictionary will contain a key and value for every field in the database table.
*fields 如果指出它就会限制SELECT 如果你指出了此字段 每个字典会只包含你指出的这个字段的KEY / VALUE 如果你没有指出字段,每个字典会包含数据库table中的所有字段的KEY /VALUE
Example: 例子
>>> Blog.objects.values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]
A ValuesQuerySet is useful when you know you’re only going to need values from a small number of the available fields and you won’t need the functionality of a model instance object. It’s more efficient to select only the fields you need to use.
ValuesQuerySet 在你想在大量的值中只有一小部分是你想用的fields时 你不需要大量的模型对象实例 它更高效
Finally, note a ValuesQuerySet is a subclass of QuerySet, so it has all methods of QuerySet. You can call filter() on it, or order_by(), or whatever. Yes, that means these two calls are identical:
最后注意ValueQuerySet是Query Set的一个字集它拥有QuerySet所有的方法
Blog.objects.values().order_by('id')
Blog.objects.order_by('id').values()
The people who made Django prefer to put all the SQL-affecting methods first, followed (optionally) by any output-affecting methods (such as values()), but it doesn’t really matter. This is your chance to really flaunt your individualism.
制作django的人宁愿把所有SQL受第一影响,其次是(可选择)任何输出影响的方法但 并不真的重要,这是你彰显个性的机会


===================================================================================

Related objects
When you define a relationship in a model (i.e., a ForeignKey, OneToOneField, or ManyToManyField), instances of that model will have a convenient API to access the related object(s).
当你定义了一个MODEL的关系时(例如外键,一个单对多的域或是多对多的字域)将会有一个可以方便访问关系数据对象的API
Using the models at the top of this page, for example, an Entry object e can get its associated Blog object by accessing the blog attribute: e.blog.
在上面一章中讲到了利用model , 例如:一个E ntry 对象能够得到Bolg的associated对象通过对bolg属性的访问
(Behind the scenes, this functionality is implemented by Python descriptors. This shouldn’t really matter to you, but we point it out here for the curious.)
这个功能在幕后是通过python实现的,你不必在意它,不过我们必须在现在指出来
Django also creates API accessors for the “other” side of the relationship — the link from the related model to the model that defines the relationship. For example, a Blog object b has access to a list of all related Entry objects via the entry_set attribute: b.entry_set.all().
Django 也可以创建访问关系另一面的API ---定义MODEL与MODEL的关系,例如:一个bolg对象通过entry_set 的属性: b.entry_set.all()可以访问所有关系对象的列表
All examples in this section use the sample Blog, Author and Entry models defined at the top of this page.
在这章中所有的简单的blog的例子,Auther 和 Entry 模型都定义在文章的上面
One-to-many relationships 单对多的关系
Forward 如下
If a model has a ForeignKey, instances of that model will have access to the related (foreign) object via a simple attribute of the model.
如果一个模型有一个外键,(那它通过)模型的一个实例将可以通过一个模型属性来访问(外键)关系对象
Example:
e = Entry.objects.get(id=2)
e.blog # Returns the related Blog object.返回Bolg的关系对象
You can get and set via a foreign-key attribute. As you may expect, changes to the foreign key aren’t saved to the database until you call save().
正如你所希望的 你可以get 和 set 一个外键属性 改变外键并不能保存到数据库直到你调用save()
Example:
e = Entry.objects.get(id=2)
e.blog = some_blog
e.save()
If a ForeignKey field has null=True set (i.e., it allows NULL values), you can assign None to it.
如果一个外键的域有null = True 设置(例如:它允许空值) 你可以不给它赋任何值
Example:
e = Entry.objects.get(id=2)
e.blog = None
e.save() # "UPDATE blog_entry SET blog_id = NULL ...;"
Forward access to one-to-many relationships is cached the first time the related object is accessed. Subsequent accesses to the foreign key on the same object instance are cached. Example:
面向访问一对多的关系访问的是在第一次访问被缓存的关系对象
e = Entry.objects.get(id=2)
print e.blog  # Hits the database to retrieve the associated Blog.
              #触及了关于bolg的关系型数据库
print e.blog  # Doesn't hit the database; uses cached version.
              #没有触及数据库,利用的是缓存的对象
Note that the select_related() QuerySet method recursively prepopulates the cache of all one-to-many relationships ahead of time.
注意:select_related()数据集的方法调用的是在第一时间预缓存的一对多的关系
Example:
e = Entry.objects.select_related().get(id=2)
print e.blog  # Doesn't hit the database; uses cached version.
print e.blog  # Doesn't hit the database; uses cached version.
              #不触及数据库,利用缓存对象
select_related() is documented in the QuerySet methods that return new QuerySets section above.
Select_related()是在QuerySet methods that return new QuerySets章节中的文档
Backward  回滚
If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. By default, this Manager is named FOO_set, where FOO is the source model name, lowercased. This Manager returns QuerySets, which can be filtered and manipulated as described in the “Retrieving objects” section above.
如果一个模型有外键,外键模型的实例子可以访问第一模型的所有实例的管理,这个管理被命名成FOO_set FOO是源模型的名字 小写的 正如上章在“对象间的关系”中描述的管理者可以过滤和处理返回结果集
Example:
Blog.entry_set # Raises AttributeError: "Manager must be accessed via instance".
In addition to the QuerySet methods defined in “Retrieving objects” above, the ForeignKey Manager has these additional methods:
数据集的方法定义在“对象之间的关系”中,外键管理者拥有这些增加的方法
·         add(obj1, obj2, ...): Adds the specified model objects to the related object set.
·         增加一个指定对象的方法到关系对象设置中
Example:
b = Blog.objects.get(id=1)
b.entry_set.all()
# Returns all Entry objects related to Blog.
# b.entry_set is a Manager that returns QuerySets.
b.entry_set.filter(headline__contains='Lennon')
b.entry_set.count()
You can override the FOO_set name by setting the related_name parameter in the ForeignKey() definition. For example, if the Entry model was altered to blog = ForeignKey(Blog, related_name='entries'), the above example code would look like this:
在ForeignKey()定义中通过设置related_name 参数来重写FOO_set名称,例如
如果Entry 模型 被改写成blog = ForeignKey(Blog, related_name='entries') 上面的例子会像这样:
b = Blog.objects.get(id=1)
b.entries.all()
# Returns all Entry objects related to Blog.
# b.entries is a Manager that returns QuerySets.
b.entries.filter(headline__contains='Lennon')
b.entries.count()
You cannot access a reverse ForeignKey Manager from the class; it must be accessed from an instance.
从一个类中你不能访问一个逆转的外键管理者,它必须在一个实例中访问
Example:
b = Blog.objects.get(id=1)
e = Entry.objects.get(id=234)
b.entry_set.add(e)
# Associates Entry e with Blog b.用blog对象 b 来访问e
·         create(**kwargs): Creates a new object, saves it and puts it in the related object set. Returns the newly created object.
·         创建一个新的对象,保存增加到关系对象设置中 返回一个新的对象
Example:
b = Blog.objects.get(id=1)
e = b.entry_set.create(headline='Hello', body_text='Hi', pub_date=datetime.date(2005, 1, 1))

# No need to call e.save() at this point -- it's already been saved.
#在这里指出不需要调用e.save() – 它已经被保存了

[ 本帖最后由 极品黑公子 于 2008-3-4 10:16 编辑 ]
学会怎么调试程序,学会怎么设计模式,学会怎么配置环境,学会怎么带项目,学会怎么分析客户需求

TOP

顶你个肺啊
交流QQ群2:16142493
智能手机软件下载
PHP新手不可错过一帖
PHP新手如何获得积分
论坛需要你,我们大家需要你!

TOP

引用:
原帖由 robin 于 2008-3-4 10:21 发表
顶你个肺啊
附件: 您所在的用户组无法下载或查看附件


其实,回帖也是一种美德!

TOP

think of image made

I have followed Doug Van Horn's detailed explanation very closely.  I
have also read the Django documentation page on this particular
topic.  But for some reason, I still cannot get the thing to work.

Here is my situation:  In my <full path>/Programming/Python/Django
directory I have created a project called TestProject, and in
TestProject I have an app called TestApp.

Also in TestProject I have Media/JavaScript/MyJSFile.js.  In urls.py I
have the following line:

(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '<full path>Programming/Python/Django/TestProject/
Media'}),

I have also specified '<full path>/Programming/Python/Django/
TestProject/Media' as my MEDIA_ROOT and '/media/' as MEDIA_URL in
settings.py.  I have read the documentation very carefully, and I
believe I am doing everything correctly.

I have <script type="text/javascript" src="media/JavaScript/

You are missing a leading slash before media in your src= here.  Without it the browser will request a url relative to the page you are providing (take a look at the GETs printed out by the dev server when you request the page), but your url spec for the static server requires that the 'media/' be at the beginning of the requested url.  So what you have will only work when you are serving the root page.
学会怎么调试程序,学会怎么设计模式,学会怎么配置环境,学会怎么带项目,学会怎么分析客户需求

TOP

怎么写自己的模板tag

[Django]Django 中自定义 tag 如何获取变量参数的值
摘自:http://blogger.org.cn/blog/more.asp?name=lhwork&id=23211
lhwork 发表于 2007-3-14 911

这两天学着写了个 Django 的 tag,这个 tag 叫做 "post_detail_tag", 调用的代码像这样:

{% post_detail_tag post.id current_post_id %}
其中后面两个都是传递的变量。

结果我发现在 tag 的代码中,一开始解析传递过去的 token 时,能获取到的仅仅是 "post.id", "current_post_id" 这种变量名,而无从获取其变量值。

当然了,仔细想想的确也应该这样,因为这个时候还没有 context. 传进 tag 的仅仅是 "post_detail_tag post.id current_post_id" 这个字符串罢了,还在 tokenize 的低级阶段。

因此自然想到,实际的变量值获取必须在 tag 对应的 Node 类的 render 方法中才可以获取到,因为这个时候参数中会传进来 context.

奇怪的是获取变量值这样一个常见的需求却没有在文档中看到说明,相关范例代码里也找不到。也许是我看的不仔细吧。。

翻看 D:\Python24\Lib\site-packages\Django-0.95.1-py2.4.egg\django\template\__init__.py 的源代码才找到 resolve_variable 这个函数。另外对于 FilterExpression 而言也有 resolve 函数,但这个内部还是调用 resolve_variable 的。因此导入这个函数试了一下,发现可以取到变量的值了。

代码:
from django import template
from django.template import Context, Template, loader, resolve_variable

register = template.Library()

class PostDetailNode(template.Node):
    def __init__(self, id, current_post_id):
        self.id = id
        self.current_post_id = current_post_id        
        pass
   
    def render(self, context):      
        current_post_id = int(resolve_variable(self.current_post_id, context))        
        context['current_post_id'] = current_post_id
        t = loader.get_template("forum/templatetags/post_detail.html")        
        return t.render(context)

#@register.tag(name='post_detail_tag')
def do_post_detail_tag(parser, token):
    try:
        #tag_name, args = token.contents.split(None, 1)
        #id, current_post_id = args.split(None, 1)
        tag_name, id, current_post_id = token.split_contents()
        print id, current_post_id
    except ValueError:        
        raise template.TemplateSyntaxError, "%s tag requires argument" % tag_name
   
    return PostDetailNode(id, current_post_id)

register.tag('post_detail_tag', do_post_detail_tag)
学会怎么调试程序,学会怎么设计模式,学会怎么配置环境,学会怎么带项目,学会怎么分析客户需求

TOP

发新话题