Skip to content

CallbackData

Bases: Model

Store callback data for Telegram inline keyboards.

This is required because telegram limits the size of callback data to 64 bytes.

Source code in django_telegram_app/models.py
class CallbackData(models.Model):
    """Store callback data for Telegram inline keyboards.

    This is required because telegram limits the size of callback data to 64 bytes.
    """

    if TYPE_CHECKING:
        data: models.JSONField[dict[str, Any]]

    token = models.UUIDField(verbose_name=_("token"), default=uuid.uuid4, unique=True, db_index=True)
    command = models.CharField(verbose_name=_("command"), max_length=255)
    step = models.CharField(verbose_name=_("step"), max_length=255)
    action = models.CharField(
        verbose_name=_("action"),
        max_length=99,
        help_text=_("Name of a function on the command"),
    )
    data = models.JSONField(verbose_name=_("callback data"), default=dict, encoder=DjangoJSONEncoder)
    created_at = models.DateTimeField(verbose_name=_("created at"), auto_now_add=True)

    class Meta:
        """Set meta options."""

        verbose_name = _("callback data")
        verbose_name_plural = _("callback data")
        indexes = [models.Index(models.F("data__correlation_key"), name="callback_correlation_key_idx")]

    def __str__(self):
        """Return a string representation of the callback data."""
        return f"{self.token} - {self.data_truncated}"

    @property
    def data_truncated(self):
        """Return the data truncated to 100 characters."""
        data_str = str(self.data)
        if len(data_str) > 100:
            return data_str[:97] + "..."
        return data_str

data_truncated property

Return the data truncated to 100 characters.

Meta

Set meta options.

Source code in django_telegram_app/models.py
class Meta:
    """Set meta options."""

    verbose_name = _("callback data")
    verbose_name_plural = _("callback data")
    indexes = [models.Index(models.F("data__correlation_key"), name="callback_correlation_key_idx")]

__str__()

Return a string representation of the callback data.

Source code in django_telegram_app/models.py
def __str__(self):
    """Return a string representation of the callback data."""
    return f"{self.token} - {self.data_truncated}"