Django-MySQL extends Django's built-in MySQL and MariaDB support their specific features not available on other databases.

Overview

Django-MySQL

https://img.shields.io/readthedocs/django-mysql?style=for-the-badge https://img.shields.io/github/workflow/status/adamchainz/django-mysql/CI/main?style=for-the-badge https://img.shields.io/codecov/c/github/adamchainz/django-mysql/main?style=for-the-badge https://img.shields.io/pypi/v/django-mysql.svg?style=for-the-badge https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge pre-commit
The dolphin-pony - proof that cute + cute = double cute.
The dolphin-pony - proof that cute + cute = double cute.

Django-MySQL extends Django's built-in MySQL and MariaDB support their specific features not available on other databases.

What kind of features?

Includes:

  • QuerySet extensions:
    • 'Smart' iteration - chunked pagination across a large queryset
    • approx_count for quick estimates of count()
    • Query hints
    • Quick pt-visual-explain of the underlying query
  • Model fields:
    • MariaDB Dynamic Columns for storing dictionaries
    • Comma-separated fields for storing lists and sets
    • 'Missing' fields: differently sized BinaryField/TextField classes, BooleanFields represented by BIT(1)
  • ORM expressions for over 20 MySQL-specific functions
  • A new cache backend that makes use of MySQL's upsert statement and does compression
  • Status variable inspection and utility methods
  • Named locks for easy locking of e.g. external resources
  • Table lock manager for hard to pull off data migrations

To see them all, check out the exposition at https://django-mysql.readthedocs.io/en/latest/exposition.html .

Requirements and Installation

Please see https://django-mysql.readthedocs.io/en/latest/installation.html .

Documentation

Every detail documented on Read The Docs.

Comments
  • Add EnumField

    Add EnumField

    Fixes #140 . As requested, I'm opening this pull request early so that we can discuss any design details on github. I'll probably get a chance to continue working on this again on Wednesday or Thursday.

    opened by MichaelAquilina 19
  • Fixed problem with control characters in JSONField

    Fixed problem with control characters in JSONField

    Summary: Added option strict=False to the json.loads call in the from_db_value method of the JSONField class to allow control characters. Fixes #287.

    Checklist:

    • [x] Docs updated - N/A
    • [x] Line added to HISTORY.rst
    • [x] All commits squashed into one.

    Test Plan: Added test

    opened by marco-santamaria 18
  • django.db.utils.OperationalError: (1101,

    django.db.utils.OperationalError: (1101, "BLOB, TEXT, GEOMETRY or JSON column 'attrs' can't have a default value")

    Server version: 5.7.20 MySQL Community Server (GPL) mysqlclient (1.3.12) Django (1.8.18)

    Hello,there i have a problem i've created a json field like below: from django_mysql.models import JSONField,ListCharField class express_model(models.Model): ''' 快递公司名单 ''' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) exp_code = models.CharField(u'快递公司代码', max_length=10,blank=True, null=True) exp_name = models.CharField(u'快递公司名称', max_length=50) attrs = JSONField(default=my_default)

    then there's ERRORS:

    File "manage.py", line 14, in execute_from_command_line(sys.argv) File "/usr/lib/python2.7/site-packages/django/core/management/init.py", line 354, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/site-packages/django/core/management/init.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/usr/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 222, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/usr/lib/python2.7/site-packages/django/db/migrations/executor.py", line 110, in migrate self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial) File "/usr/lib/python2.7/site-packages/django/db/migrations/executor.py", line 148, in apply_migration state = migration.apply(state, schema_editor) File "/usr/lib/python2.7/site-packages/django/db/migrations/migration.py", line 115, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards field, File "/usr/lib/python2.7/site-packages/django/db/backends/mysql/schema.py", line 43, in add_field super(DatabaseSchemaEditor, self).add_field(model, field) File "/usr/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 398, in add_field self.execute(sql, params) File "/usr/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 111, in execute cursor.execute(sql, params) File "/usr/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/lib/python2.7/site-packages/django/db/utils.py", line 98, in exit six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 124, in execute return self.cursor.execute(query, args) File "/usr/lib64/python2.7/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/usr/lib64/python2.7/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue django.db.utils.OperationalError: (1101, "BLOB, TEXT, GEOMETRY or JSON column 'attrs' can't have a default value")

    Can somebody figure out what happend? is because STRICT MODE? and here's my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'euler_lims', 'USER':'', 'PASSWORD':'', 'HOST':'localhost', 'PORT':'3306', 'OPTIONS' : { 'charset': 'utf8mb4', 'init_command': "SET sql_mode='STRICT_TRANS_TABLES', innodb_strict_mode=1", } }, 'TEST': { 'CHARSET': 'utf8mb4', 'COLLATION': 'utf8mb4_unicode_ci', } }

    opened by haoziyeung 17
  • Storing strings in JSONField.

    Storing strings in JSONField.

    Be able to store strings in JSONField (this feature was broken).

    Also copy code from 'django.contrib.postgres.forms.jsonb.JSONField' in order to fix some issues related with redisplaying wrong user input.

    This PR is motivated by: #349 (which now it is not longer necessary).

    Checklist:

    • [x] Line added to HISTORY.rst, or N/A

    Test Plan:

    • Create some test about serializing strings.
    • Copy two tests from ' django.tests.postgres_tests.test_json.py'.
    • All current and new tests pass.
    opened by arnau126 12
  • AttributeError: 'DatabaseWrapper' object has no attribute 'is_mariadb'

    AttributeError: 'DatabaseWrapper' object has no attribute 'is_mariadb'

    When i am running the makemigration command for this model

    from __future__ import unicode_literals
    
    from django.db import models
    from django_mysql.models import JSONField
    
    class Owners(models.Model):
        name = models.CharField(max_length=255)
        url = models.CharField(max_length=128, null=True, blank=True)
        email = models.EmailField(null=True, blank=True)
        phone = models.CharField(max_length=32, null=True, blank=True)
        address = models.CharField(max_length=128, null=True, blank=True)
        country = models.CharField(max_length=32, null=True, blank=True)
        description = models.TextField(null=True, blank=True)
    
    class Brands(models.Model):
        name = models.CharField(max_length=255)
        owner = models.ForeignKey(Owners, null=True, blank=True)
        url = models.CharField(max_length=128, null=True, blank=True)
        description = models.TextField(null=True, blank=True)
        tags = JSONField(null=True, blank=True)
    

    I am getting that logs

      File "/home/sanyam/Project/groceryfy/venv/local/lib/python2.7/site-packages/django_mysql/models/fields/json.py", line 65, in _check_mysql_version
        (conn.is_mariadb or conn.mysql_version < (5, 7))
    AttributeError: 'DatabaseWrapper' object has no attribute 'is_mariadb'
    

    Summary: summarize the issue here

    If this is a bug, please fill in the below, else delete

    Django Version: e.g. Django 1.9

    Database and version used: e.g. MySQL 5.7

    Version: e.g. Django-MySQL 1.1.0

    opened by Sanyambansal76 12
  • ImportError: No module named termios on Windows

    ImportError: No module named termios on Windows

    Summary: https://stackoverflow.com/questions/36508126/importerror-no-module-named-termios-with-django-mysql-on-windows

    Django Version: 1.8.7 Database and version used: MySQL 5.6 Version: Django-MySQL 1.0.7

    Even after installing Cygwin.

    opened by MrCsabaToth 12
  • Support __icontains lookup on JSONField

    Support __icontains lookup on JSONField

    Summary: NotImplementedError at /api/table/ Lookup 'icontains' doesn't work with JSONField (when try do a searh including one JSONField

    Django Version: Django 1.11.3

    Database and version used: community-mysql-5.7.18-2.fc25.x86_64

    Version: django-filter (1.0.4) django-mysql (2.1.0) djangorestframework (3.6.3)

    NotImplementedError at /api/table/ Lookup 'icontains' doesn't work with JSONField

    key | value -- | -- Request Method: | GET Request URL: | http://127.0.0.1:51002/api/table/?search=ICT Django Version: | 1.11.3 Exception Type: | NotImplementedError Exception Value: | Lookup 'icontains' doesn't work with JSONField Exception Location: | /usr/lib/python3.5/site-packages/django_mysql/models/fields/json.py in get_lookup, line 124 Python Executable: | /usr/bin/python3 Python Version: | 3.5.3

    like I wrote , should something similar to https://github.com/adamchainz/django-mysql/pull/368 register icontains and the SQL is simple like :

    SELECT * FROM table WHERE json_field COLLATE utf8mb4_unicode_ci LIKE '%ICT%' 
    
    opened by sergiomb2 11
  • JSONField default passed to SQL create column query

    JSONField default passed to SQL create column query

    Summary: Migrations created to add a JSONField include default, causing query to fail.

    Django Version: Django 1.9.2-8

    Database and version used: MySQL 5.7.11

    Version: Django-MySQL 1.0.1

    Hi, I've been having some inconsistent behaviour with this so sorry if this is confusing. In the current situation I'm stuck in, I have model that was created with a JSONField without any problems, and I'm trying to add another JSONField. It keeps failing because the migrations tries to set a default on the field, which MySQL doesn't allow: (django.db.utils.OperationalError: (1101, "BLOB, TEXT, GEOMETRY or JSON column 'tables' can't have a default value")) I think I know why this is happening: https://github.com/django/django/blob/6bf7964023487f2a352084e74aca27aecb354d6c/django/db/backends/mysql/schema.py#L28 That method tells migrations to leave out the default for certain fields, and I believe JSONField would now need to be included among those, as the django_mysql JSONField implicitly sets dict as its default.

    I can't immediately see how this could be rectified here. Do you think it requires a bug report for Django? Or maybe I've overlooked something.

    I know I've left out full tracebacks and stuff but that's just because I'm pretty sure I've located the issue above. Let me know if you'd like more.

    opened by ConorMcGee 11
  • Add functions for Django 1.8+

    Add functions for Django 1.8+

    Resolves #12 .

    To do:

    • MD5 / SHA1 / SHA2 - https://mariadb.com/kb/en/mariadb/encryption-functions/
    • LAST_VALUE - https://mariadb.com/kb/en/mariadb/last_value/ - which then suggests doing mysql-side vars
    • SLEEP - https://mariadb.com/kb/en/mariadb/sleep/
    • CEILING/FLOOR - https://mariadb.com/kb/en/mariadb/ceiling/ / https://mariadb.com/kb/en/mariadb/floor/
    • HEX - https://mariadb.com/kb/en/mariadb/hex/

    Maybe better as 'lookups' or custom field types:

    • FROM/TO_BASE64 - https://mariadb.com/kb/en/mariadb/to_base64/ / https://mariadb.com/kb/en/from_base64/
    • Some MariaDB specific regex functions https://mariadb.com/kb/en/mariadb/regular-expressions-functions/
    opened by adamchainz 11
  • Prevent JSONField from adding CAST(... AS JSON) for str/int/float

    Prevent JSONField from adding CAST(... AS JSON) for str/int/float

    Fixes #480 . Only cast to json the right hand side expression if it is a dict, a list or a tuple.

    Example: Before: WHERE JSON_EXTRACT(tabledoc.field, '$.sub_field') = (CAST('\"value\"' AS JSON)); After: WHERE JSON_EXTRACT(tabledoc.field, '$.sub_field') = ("value");

    opened by arnau126 10
  • charset + collation transformer (fix utf8mb4)

    charset + collation transformer (fix utf8mb4)

    Add a command that does ALTER DATABASE, and ALTER TABLE as required to change character set for the database from utf8 to utf8mb4, or rather, from any arbitrary charset + collation to any other.

    Don't forget to remove the note in the checks docs about this being WIP.

    feature 
    opened by adamchainz 10
  • Add support for natural sorting with MariaDB 10.7+ `NATURAL_SORT_KEY`

    Add support for natural sorting with MariaDB 10.7+ `NATURAL_SORT_KEY`

    Description

    It would be great to be able to sort by NATURAL_SORT_KEY.

    Possibly the following could be supported for the syntax (to natsort by the name column):

    Document.objects.order_by("NATURAL_SORT_KEY(name)")
    

    Thanks

    opened by violuke 3
  • Add support for filter expression in GroupConcat

    Add support for filter expression in GroupConcat

    Fixes #947.

    GroupConcat did not support fitler expression. This PR adds support based on Django Count aggregate.

    https://github.com/adamchainz/django-mysql/blob/main/src/django_mysql/models/aggregates.py

    opened by caramdache 3
  • GroupConcat missing `filter` parameter

    GroupConcat missing `filter` parameter

    Description

    Native Django aggregates support a filter parameter that allow a subset of expressions to be returned. For example:

    .annotate(count=Count("expr", filter=filter_expr))
    

    which generates the following SQL:

    COUNT(DISTINCT CASE WHEN <filter_expr> THEN <expr> ELSE NULL END) as count
    

    However the filter parameter is ignored today by GroupConcat and I'm not quite sure how to add it to the source code.

    opened by caramdache 4
  • Support JSON functions only on MariaDB

    Support JSON functions only on MariaDB

    There are quite a few JSON functions added on MariaDB 10.2+ we should support: https://mariadb.com/kb/en/library/function-differences-between-mariadb-102-and-mysql-57/

    opened by adamchainz 1
  • Re-activate testing on MySQL and MariaDB 5.5

    Re-activate testing on MySQL and MariaDB 5.5

    In #388 testing on these databases was removed because I couldn't figure out how to force install them - apt refuses to by default as there are packages providing MySQL 5.6 in the Ubuntu default repos. There are some hints in the MariaDB docs on how to work around this - I tried pinning the repo but it didn't seem to work: https://mariadb.com/kb/en/library/installing-mariadb-deb-files/#installation-issues

    opened by adamchainz 1
Owner
Adam Johnson
🦄 @django technical board member 🇬🇧 @djangolondon co-organizer ✍ AWS/Django/Python Author and Consultant
Adam Johnson
With Django Hijack, admins can log in and work on behalf of other users without having to know their credentials.

Django Hijack With Django Hijack, admins can log in and work on behalf of other users without having to know their credentials. Docs 3.x docs are avai

null 1.2k Jan 5, 2023
Notes-Django: an advanced project to save notes in Django. where users are able to Create, Read, Update and Delete their notes.

An advanced software to keep you notes. It allows users to perform CRUD operations on theirs Notes. Was implemented Authorization and Authentication

Edilson Pateguana 1 Feb 5, 2022
A handy tool for generating Django-based backend projects without coding. On the other hand, it is a code generator of the Django framework.

Django Sage Painless The django-sage-painless is a valuable package based on Django Web Framework & Django Rest Framework for high-level and rapid web

sageteam 51 Sep 15, 2022
✋ Auto logout a user after specific time in Django

django-auto-logout Auto logout a user after specific time in Django. Works with Python ?? ≥ 3.7, Django ?? ≥ 3.0. ✔️ Installation pip install django-a

Georgy Bazhukov 21 Dec 26, 2022
CRUD with MySQL, Django and Sass.

CRUD with MySQL, Django and Sass. To have the same data in db: insert into crud_employee (first_name, last_name, email, phone, location, university) v

Luis Quiñones Requelme 1 Nov 19, 2021
REST API con Python, Django y MySQL (GET, POST, PUT, DELETE)

django_api_mysql REST API con Python, Django y MySQL (GET, POST, PUT, DELETE) REST API con Python, Django y MySQL (GET, POST, PUT, DELETE)

Andrew 1 Dec 28, 2021
Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project

Django URL Shortener Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project Install this package to your Dja

Rishav Sinha 4 Nov 18, 2021
Neighbourhood - A python-django web app to help the residence of a given neighborhood know their surrounding better

Neighbourhood A python-django web app to help the residence of a given neighborh

Levy Omolo 4 Aug 25, 2022
django social media app with real time features

django-social-media django social media app with these features: signup, login and old registered users are saved by cookies posts, comments, replies,

null 8 Apr 30, 2022
Django friendly finite state machine support

Django friendly finite state machine support django-fsm adds simple declarative state management for django models. If you need parallel task executio

Viewflow 2.1k Dec 31, 2022
This is a simple Todo web application built Django (back-end) and React JS (front-end)

Django REST Todo app This is a simple Todo web application built with Django (back-end) and React JS (front-end). The project enables you to systemati

Maxim Mukhin 5 May 6, 2022
Fully reponsive Chat Application built with django, javascript, materialUi, bootstrap4, html and css.

Chat app (Full Stack Frameworks with Django Project) Fully reponsive Chat Application built with django, javascript, materialUi, bootstrap4, html and

null 1 Jan 19, 2022
Djangoblog - A blogging platform built on Django and Python.

djangoblog ??‍?? A blogging platform built on Django and Python

Lewis Gentle 1 Jan 10, 2022
A Student/ School management application built using Django and Python.

Student Management An awesome student management app built using Django.! Explore the docs » View Demo · Report Bug · Request Feature Table of Content

Nishant Sethi 1 Feb 10, 2022
Comprehensive Markdown plugin built for Django

Django MarkdownX Django MarkdownX is a comprehensive Markdown plugin built for Django, the renowned high-level Python web framework, with flexibility,

neutronX 738 Dec 21, 2022
A Blog Management System Built with django

Blog Management System Backend use: Django Features Enhanced Ui

Vishal Goswami 1 Dec 6, 2021
Flashback is an awesome, retro IRC based app built using Django

Flashback Flashback is an awesome, retro IRC based app built using Django (and the Django Rest Framework) for the backend as well as React for the fro

Unloading Gnat 1 Dec 22, 2021
A CTF leaderboard for the submission of flags during a CTF challenge. Built using Django.

?? CTF Leaderboard The goal of this project is to provide a simple web page to allow the participants of an CTF to enter their found flags. Also the l

Maurice Bauer 2 Jan 17, 2022
This is a repository for a web application developed with Django, built with Crowdbotics

assignment_32558 This is a repository for a web application developed with Django, built with Crowdbotics Table of Contents Project Structure Features

Crowdbotics 1 Dec 29, 2021