Making queries

The QDjango object relational mapper (ORM) supports the concept of querysets, borrowed from django's ORM.

A queryset is a collection of database objects which match a certain number of user-specified conditions.

You can learn more about querysets by reading the QDjangoQuerySet template class documentation.

Creating and filtering querysets

Before you can start using querysets, you need to declare your database models as described in Database models.

The most basic queryset matches all the objects for a given model.

// all users

You can use the QDjangoQuerySet::filter() and QDjangoQuerySet::exclude() methods to add filtering conditions to a querset:

// find all users whose password is "foo" and whose username is not "bar"
someUsers = users.filter(QDjangoWhere("password", QDjangoWhere::Equals, "foo") &&
QDjangoWhere("username", QDjangoWhere::NotEquals, "bar"));
// find all users whose username is "foo" or "bar"
someUsers = users.filter(QDjangoWhere("username", QDjangoWhere::Equals, "foo") ||
QDjangoWhere("username", QDjangoWhere::Equals, "bar"));
// find all users whose username starts with "f":
someUsers = users.filter(QDjangoWhere("username", QDjangoWhere::StartsWith, "f"));

You can also use the QDjangoQuerySet::limit() method to limit the number of returned rows:

// limit number of results
someUsers = users.limit(0, 100);

Iterating over results

The easiest way to iterate over results is to use Qt's foreach keyword:

// iterate over matching users
foreach (const User &user, someUsers) {
qDebug() << "found user" << user.username;

Another way of iterating over results is to run over model instances using the QDjangoQuerySet::size() and QDjangoQuerySet::at() methods:

// iterate over matching users
User user;
for (int i = 0; i < someUsers.size(); ++i) {
if (someUsers.at(i, &user)) {
qDebug() << "found user" << user.username;

It is also possible to retrieve field data without creating model instances using the QDjangoQuerySet::values() and QDjangoQuerySet::valuesList() methods:

// retrieve usernames and passwords for matching users as maps
QList<QVariantMap> propertyMaps = someUsers.values(QStringList() << "username" << "password");
foreach (const QVariantMap &propertyMap, propertyMaps) {
qDebug() << "username" << propertyList["username"];
qDebug() << "password" << propertyList["password"];
// retrieve usernames and passwords for matching users as lists
QList<QVariantList> propertyLists = someUsers.valuesList(QStringList() << "username" << "password");
foreach (const QVariantList &propertyList, propertyLists) {
qDebug() << "username" << propertyList[0];
qDebug() << "password" << propertyList[1];

Other operations

// count matching users without retrieving their data
int numberOfUsers = someUsers.count();
// delete all the users in the queryset