Database models

Database models are usually created by subclassing the QDjangoModel class.

The following example defines a User model suitable for storing basic account information, and illustrate different types of queries on this model.

Declaring your model

To declare your model, subclass the QDjangoModel class, and define a property using the Q_PROPERTY macro for each database field. You can provide additional information about a field using the Q_CLASSINFO macro:

#include "QDjangoModel.h"
class User : public QDjangoModel
Q_PROPERTY(QString username READ username WRITE setUsername)
Q_PROPERTY(QString password READ password WRITE setPassword)
Q_CLASSINFO("username", "max_length=255")
Q_CLASSINFO("password", "max_length=128")
QString username() const;
void setUsername(const QString &username);
QString password() const;
void setPassword(const QString &password);
QString m_username;
QString m_password;

Implementing your model

QString User::username() const
return m_username;
void User::setUsername(const QString &username)
m_username = username;
QString User::password() const
return m_password;
void User::setPassword(const QString &password)
m_password = password;

Registering and using your model

To make your model available for database operations, you should now register your model using:


Once you have set the database (see Database configuration), you will now be able to create model instances and save them to the database:

User *user = new User;

.. or remove them from the database:


You can also perform operations such as filtering or retrieving model instances as described in Making queries.

Using QDjango without QDjangoModel

Although it is recommended you make your models inherit QDjangoModel, it is not strictly necessary. QDjango can in fact handle any QObject-derived class, but you will lose some of the syntactic sugar.

If for instance you defined a SomeObject class which inherits QObject, you can write:

QDjangoMetaModel meta = QDjango::registerModel<SomeObject>();
// prepare a SomeObject instance
SomeObject *obj = new SomeObject;
obj->setSomeProperty("some value");
obj->setOtherProperty("other value");
// save the object
// remove the object from database