您的位置:首页 > 产品设计 > UI/UE

Django QuerySet API

2013-11-21 15:34 525 查看


https://docs.djangoproject.com/en/1.4/ref/models/querysets/#distinct

每天几个新方法:


1.distinct

distinct([*fields])

Returns a new QuerySet that uses SELECT DISTINCT in
its SQL query. This eliminates duplicate rows from the query results.

As of Django 1.4, you can pass positional arguments (*fields) in order to specify the names of fields to which the DISTINCTshould
apply. This translates to a SELECT DISTINCT ON SQL
query.

Here’s the difference. For a normal distinct() call, the database compares each field
in each row when determining which rows are distinct. For a distinct() call with specified field names, the database will only compare the
specified field names.


2.using

using(alias)

New in Django 1.2.

This method is for controlling which database the QuerySet will be evaluated against if you are using more than one database. The only argument
this method takes is the alias of a database, as defined in DATABASES.


3.values

values(*fields)

Returns a ValuesQuerySet — a QuerySet subclass
that returns dictionaries when used as an iterable, rather than model-instance objects.

Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.

This example compares the dictionaries of values() with the normal model objects:
The values() method
takes optional positional arguments, *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.
>>> Blog.objects.values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]


4.values_list


values_list(*fields)

New in Django 1.0: Please, see the release notes

This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over. Each tuple contains the value from the respective field passed into the values_list() call
-- so the first item is the first field, etc. For example:

>>> Entry.objects.values_list('id', 'headline')
[(1, u'First entry'), ...]


If you only pass in a single field, you can also pass in the flat parameter. If True, this will mean the returned results are single values, rather than one-tuples. An example should make
the difference clearer:

>>> Entry.objects.values_list('id').order_by('id')
[(1,), (2,), (3,), ...]

>>> Entry.objects.values_list('id', flat=True).order_by('id')
[1, 2, 3, ...]


It is an error to pass in flat when there is more than one field.

If you don't pass any values to values_list(), it will return all the fields in the model, in the order they were declared.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: