Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django model field comment in database

Tags:

django

this is the model class(django version 2.0)

class Host(models.Model):
    host_id=models.CharField(max_length=20,primary_key=True)
    host_label=models.CharField(verbose_name="linux_host_label",max_length=255)

the table structrue in database

mysql> show create table dashboard_host;
| dashboard_host | CREATE TABLE `dashboard_host` (
  `host_id` varchar(20) NOT NULL,
  `host_label` varchar(255) NOT NULL,
  PRIMARY KEY (`host_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |

but how to do in the model class to get like this

mysql> show create table dashboard_host;
| dashboard_host | CREATE TABLE `dashboard_host` (
  `host_id` varchar(20) NOT NULL COMMENT '主机id',
  `host_label` varchar(255) NOT NULL COMMENT '主机标签',
  PRIMARY KEY (`host_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |
+----------------+-----------------------------------
like image 270
chenjun Avatar asked May 30 '18 07:05

chenjun


Video Answer


2 Answers

well there is no such way in django from the model directly. you can check the ticket https://code.djangoproject.com/ticket/24638

but you can do one thing,

first makemigrations your app and then edit the migration file and place

  CREATE TABLE `dashboard_host` (
  `host_id` varchar(20) NOT NULL COMMENT '主机id',
  `host_label` varchar(255) NOT NULL COMMENT '主机标签',
  PRIMARY KEY (`host_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

inplace of the sql query automatically generated by django

and then migrate

like image 66
Exprator Avatar answered Nov 15 '22 09:11

Exprator


Looks like currently you can't, at least not in Django. I was able to find 2 similar request tickets in Django:

#13867 Feature request: Comments in Django models saved to database schema

Opened 9 years ago and dismissed as wontfix an year later, with rationale along the lines of "it doesn't have a good usefulness/noise ratio. The ORM doesn't aim at providing a Python interface for every feature of the supported database engine"

#18468 Add the ability to define comments in table / columns

Opened 7 years ago, marked as a duplicate of the above, end of story until... plot twist! Reopened on 2018-03, went trough discussion on mailing list, and now marked as Accepted. Original rejecter said "I think we could implement that feature. (Yes I changed my mind from six years ago when I wontfix'd the ticket.)"

So now this only requires an implementation / patch / PR , which hasn't been done yet (but anyone can contribute!)

The ticket submitter started making a patch, and created a Django App that fixes the problem for Fields (using verbose_name and help_text attributes) on PostgreSQL backends. You're using MySQL, but it might be trivial to adapt it:

https://github.com/vanadium23/django-db-comments

like image 45
MestreLion Avatar answered Nov 15 '22 09:11

MestreLion