简体   繁体   中英

Django : How we can add extra fields on the Group model

Hi I am working on django permissions system with Django 2+ . And I want to add extra fields inside the Group model in Django but right now I have no idea how to do that. I tried something like:

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))

But when I migrate my model then it throwing error as:

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'  

Try this, (Not in the Group class)

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

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

In order to modify an existing model you have to inherit from the model:

from django.contrib.auth.models import Group


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

Using the add_to_class means relying on undocumented internals which have no stability guarantee, and is subject to change without warning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM