Django:我们如何在Group模型上添加额外的字段

问题描述

嗨,我正在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'  

解决方法

尝试一下,(不在Group类中)

# models.py
from django.contrib.auth.models import Group

Group.add_to_class('description',models.CharField(max_length=180,null=True,blank=True))

,

要修改现有模型,您必须从模型继承:

from django.contrib.auth.models import Group


class CustomGroup(Group):
    description = models.CharField(max_length=180,blank=True)
    

使用add_to_class意味着依赖未记录的 内部没有稳定性保证,并且 如有更改,恕不另行通知。