以编程方式创建django组

b17*_*662 10 django django-permissions

我想以编程方式在django中创建组,但不是在视图中创建组,而是在模型中创建组(例如使用迁移).怎么做?谷歌和文档中没有关于它的信息(至少不在这里:https://docs.djangoproject.com/en/1.7/topics/auth/default/#groups)

Mik*_*one 12

好吧,看来你正在使用Django 1.7的新迁移系统.这与南方相似但不完全一样.

涉及更改表中数据的迁移数据迁移,您通常需要编写Python代码来执行迁移.

从Django文档中可以看出这个例子:

# -*- coding: utf-8 -*-
from django.db import models, migrations

def combine_names(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Person = apps.get_model("yourappname", "Person")
    for person in Person.objects.all():
        person.name = "%s %s" % (person.first_name, person.last_name)
        person.save()

class Migration(migrations.Migration):

    dependencies = [
        ('yourappname', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(combine_names),
    ]
Run Code Online (Sandbox Code Playgroud)

请注意,迁移期间运行的代码位于combine_names函数中,该函数由迁移列表中的migrations.RunPython(combine_names)条目调用operations.您的迁移应该在类似的函数中创建组,以及需要的任何其他数据迁移.

你可能应该使用类似的行

Group = apps.get_model("auth", "Group")
my_group, created = Group.objects.get_or_create(name='group1')
Run Code Online (Sandbox Code Playgroud)

创建组,以防表中已有一组该名称.

在迁移到Python文件的根级别期间,不要运行代码; 如果这样做,则每次导入迁移时都会运行它,例如,每次运行时都会运行./manage.py runserver.

PS你需要把你的migrations.RunPython条目放在operations列表中的正确位置; 例如,如果将它放在删除所需表的操作之后,它将无法工作.


Dan*_*man 6

组就像任何其他Django模型一样.您可以像创建其他任何内容一样创建它们.

my_group = Group.objects.create(name='group1')
Run Code Online (Sandbox Code Playgroud)

  • @DanielRoseman:听起来像是把代码放在迁移脚本的根级别,所以它在导入时运行*.* (2认同)