db.models.SET()

SET() [source] Set the ForeignKey to the value passed to SET(), or if a callable is passed in, the result of calling it. In most cases, passing a callable will be necessary to avoid executing queries at the time your models.py is imported: from django.conf import settings from django.contrib.auth import get_user_model from django.db import models def get_sentinel_user(): return get_user_model().objects.get_or_create(username='deleted')[0] class MyModel(models.Model): user = models.

db.models.query.QuerySet.values_list()

values_list(*fields, flat=False) 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, '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 res

db.models.query.QuerySet.values()

values(*fields) Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. 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: # This list contains a Blog object. >>> Blog.objects.filter(name__startswith='Beatles') <QuerySet [<Blog: Beatles Blog>]> # This list contains a dictionary.

db.models.query.QuerySet.using()

using(alias) 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. For example: # queries the database with the 'default' alias. >>> Entry.objects.all() # queries the database with the 'backup' alias >>> Entry.objects.using('backup')

db.models.query.QuerySet.update_or_create()

update_or_create(defaults=None, **kwargs) A convenience method for updating an object with the given kwargs, creating a new one if necessary. The defaults is a dictionary of (field, value) pairs used to update the object. Returns a tuple of (object, created), where object is the created or updated object and created is a boolean specifying whether a new object was created. The update_or_create method tries to fetch an object from database based on the given kwargs. If a match is found, it up

db.models.query.QuerySet.update()

update(**kwargs) Performs an SQL update query for the specified fields, and returns the number of rows matched (which may not be equal to the number of rows updated if some rows already have the new value). For example, to turn comments off for all blog entries published in 2010, you could do this: >>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False) (This assumes your Entry model has fields pub_date and comments_on.) You can update multiple fields — there’s no l

db.models.query.QuerySet.select_related()

select_related(*fields) Returns a QuerySet that will “follow” foreign-key relationships, selecting additional related-object data when it executes its query. This is a performance booster which results in a single more complex query but means later use of foreign-key relationships won’t require database queries. The following examples illustrate the difference between plain lookups and select_related() lookups. Here’s standard lookup: # Hits the database. e = Entry.objects.get(id=5) # Hits

db.models.query.QuerySet.select_for_update()

select_for_update(nowait=False) Returns a queryset that will lock rows until the end of the transaction, generating a SELECT ... FOR UPDATE SQL statement on supported databases. For example: entries = Entry.objects.select_for_update().filter(author=request.user) All matched entries will be locked until the end of the transaction block, meaning that other transactions will be prevented from changing or acquiring locks on them. Usually, if another transaction has already acquired a lock on on

db.models.query.QuerySet.reverse()

reverse() Use the reverse() method to reverse the order in which a queryset’s elements are returned. Calling reverse() a second time restores the ordering back to the normal direction. To retrieve the “last” five items in a queryset, you could do this: my_queryset.reverse()[:5] Note that this is not quite the same as slicing from the end of a sequence in Python. The above example will return the last item first, then the penultimate item and so on. If we had a Python sequence and looked at

db.models.query.QuerySet.raw()

raw(raw_query, params=None, translations=None) Takes a raw SQL query, executes it, and returns a django.db.models.query.RawQuerySet instance. This RawQuerySet instance can be iterated over just like an normal QuerySet to provide object instances. See the Performing raw SQL queries for more information. Warning raw() always triggers a new query and doesn’t account for previous filtering. As such, it should generally be called from the Manager or from a fresh QuerySet instance.