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:

- `max_length` : the maximum length of the field (used when creating the database table)
- `primary_key` : if set to 'true', this field will be used as the primary key. If no primary key is explicitly defined, an auto-increment integer field will be added.

#include "QDjangoModel.h"
class User : public QDjangoModel
{
Q_OBJECT
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")
public:
QString username() const;
void setUsername(const QString &username);
QString password() const;
void setPassword(const QString &password);
private:
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:

QDjango::registerModel<User>();

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;
user->setUsername("someuser");
user->setPassword("somepassword");
user->save();

.. or remove them from the database:

user->remove();

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
meta.save(obj);
// remove the object from database
meta.remove(obj);