djangodocs.org

743 sections in Django 6.0 Search all versions →

Performing raw queries

Topic guide Performing raw SQL queries

The raw() manager method can be used to perform raw SQL queries that return model instances: Manager.raw(raw_query,params=(),translations=None) This method takes a raw SQL query, executes it, and returns a django.db.models.query.RawQuerySet instance.

Example

Topic guide Django shortcut functions get_list_or_404()

However, you can also pass a QuerySet instance: The above example is a bit contrived since it’s equivalent to doing: but it can be useful if you are passed the queryset variable from somewhere else.

Model managers

Topic guide Migrations Migration files

… in RunPython operations. This is done by defining a use_in_migrations attribute on the manager class: If you are using the from_queryset() function to dynamically generate a manager class, you need to inherit from the generated class to make it importable: …

Topic guide Performance and optimization General approachesGet things right from the start

For example, you might find that you could calculate the same thing - the number of items in a collection, perhaps - in a QuerySet, in Python, or in a template.

TransactionTestCase

Topic guide Testing tools Provided test case classes

classTransactionTestCase[source] TransactionTestCase inherits from SimpleTestCase to add some database-specific features: Resetting the database to a known state at the end of each test to ease testing and using the ORM. Database fixtures. Test skipping based on database backend features.

Assertions

Topic guide Testing tools Test cases features

See assertJSONEqual() for further details. TransactionTestCase.assertQuerySetEqual(qs,values,transform=None,ordered=True,msg=None)[source] : Asserts that a queryset qs matches a particular iterable of values values. TransactionTestCase.assertNumQueries(num,func,*args,**kwargs)[source] : Asserts that when func is called with *args and **kwargs that num database queries are executed.

W

Index

| | | | --- | --- | | - W3CGeoFeed (class in django.contrib.gis.feeds) - Warning (class in django.core.checks) - warp() (GDALRaster method) - WASM_UNSAFE_EVAL (CSP attribute) - week - field lookup type - week (WeekMixin attribute) - week_day - …

1.9

Internals Django Deprecation Timeline

Passing callable arguments to querysets will no longer be possible. BaseCommand.requires_model_validation will be removed in favor of requires_system_checks. Admin validators will be replaced by admin checks. The ModelAdmin.validator_class and default_validator_class attributes will be removed. ModelAdmin.validate() will be removed.

Reference

These functions are available from the django.contrib.postgres.aggregates module. They are described in more detail in the PostgreSQL docs. NOTE: All functions come without default aliases, so you must explicitly provide > one.

Key lookups

Reference PostgreSQL specific model fields HStoreFieldQuerying HStoreField

To query based on a given key, you can use that key as the lookup name: You can chain other lookups after key lookups: or use F() expressions to annotate a key value.

Database Functions

Reference

The classes documented below provide a way for users to use functions provided by the underlying database as annotations, aggregations, or filters in Django.

Some examples

Reference Query Expressions

Both the querysets below are equivalent. >>> Company.objects.filter(num_employees__gt=F("num_chairs") * 2) >>> Company.objects.filter(num_employees__gt=F("num_chairs") + F("num_chairs")) # How many chairs are needed for each company to seat all employees? >>> company = ( ... Company.objects.filter(num_employees__gt=F("num_chairs")) ... .annotate(chairs_needed=F("num_employees") - F("num_chairs")) ... .first() ...

DateTimeField

Reference Model field reference Field types

classDateTimeField(auto_now=False,auto_now_add=False,**options)[source] A date and time, represented in Python by a datetime.datetime instance. Takes the same extra arguments as DateField. The default form widget for this field is a single DateTimeInput. The admin uses two separate TextInput widgets with JavaScript shortcuts.

UUIDField

Reference Model field reference Field types

classUUIDField(**options)[source] A field for storing universally unique identifiers. Uses Python’s UUID class. When used on PostgreSQL and MariaDB 10.7+, this stores in a uuid datatype, otherwise in a char(32). Universally unique identifiers are a good alternative to AutoField for primary_key.

Arguments

Reference Model field reference Relationship fieldsManyToManyField

ForeignKey.related_name : The name to use for the relation from the related object back to this one. It’s also the default value for related_query_name (the name to use for the reverse filter name from the target model).

Accessing method calls

Reference The Django template language

… relationship to a model called “task” you can loop through all comments attached to a given task like this: Similarly, QuerySets provide a count() method to count the number of objects they contain. Therefore, you can obtain a count of …

More than just HTML

Topic guide Using mixins with class-based views

For example, a JSON mixin might look something like this: NOTE: Check out the Serializing Django objects documentation for more > information on how to correctly transform Django models and querysets into > JSON.

A full example

Topic guide Creating forms from models ModelForm

Consider this set of models: With these models, the ModelForm subclasses above would be roughly equivalent to this (the only difference being the save() method, which we’ll discuss in a moment.):