嗨,我正在用django 2+开发django权限系统。我想在Django中的Group模型中添加额外的字段,但现在我不知道如何做到这一点。我试过类似的东西:
models.py
from django.contrib.auth.models import Group
class Group(models.Model):
Group.add_to_class('description', models.CharField(max_length=180,null=True, blank=True))
但当我迁移我的模型时,它会抛出错误:
Migrations for 'auth':
/usr/local/lib/python3.6/site-packages/django/contrib/auth/migrations/0010_group_description.py
- Add field description to group
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 184, in handle
self.write_migration_files(changes)
File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 223, in write_migration_files
with open(writer.path, "w", encoding='utf-8') as fh:
PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.6/site-packages/django/contrib/auth/migrations/0010_group_description.py'
为了修改现有模型,您必须从模型中继承:
from django.contrib.auth.models import Group
class CustomGroup(Group):
description = models.CharField(max_length=180,null=True, blank=True)
使用add_to_class意味着依赖于未记录的内部构件没有稳定性保证如有变动,恕不另行通知。
试试这个(不在Group类中(
# models.py
from django.contrib.auth.models import Group
Group.add_to_class('description', models.CharField(max_length=180,null=True, blank=True))