繁体   English   中英

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

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

嗨,我正在使用 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,null=True, blank=True)
    

使用 add_to_class 意味着依赖未记录的内部结构,这些内部结构没有稳定性保证,并且可能会在没有警告的情况下发生变化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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