Python 仅定义权限的Django模型中断测试

Python 仅定义权限的Django模型中断测试,python,django,unit-testing,permissions,models,Python,Django,Unit Testing,Permissions,Models,我在应用程序模型中使用一个元类来定义应用程序级权限,没有定义实际的字段。这正如预期的那样工作,但是当我尝试运行我的测试时,我得到了django.db.utils.OperationalError:没有这样的表:xxx\u xxx。在运行单元测试时是否有排除模型的方法 class feeds(models.Model): class Meta: permissions = ( ("change_feed_defaults", "change_feed

我在应用程序模型中使用一个元类来定义应用程序级权限,没有定义实际的字段。这正如预期的那样工作,但是当我尝试运行我的测试时,我得到了django.db.utils.OperationalError:没有这样的表:xxx\u xxx。在运行单元测试时是否有排除模型的方法

class feeds(models.Model):
    class Meta:
        permissions = (
            ("change_feed_defaults", "change_feed_defaults"),
            ("view_logs", "view_logs"),
            ("preview_tagger", "preview_tagger"),
            ("preview_url", "preview_url"),
            ("view_feeds", "view_feeds"),
            ("text_tag_feedback", "text_tag_feedback"),
        )

由于您没有提供完整的堆栈跟踪,我只能猜测发生了什么

django.db.utils.OperationalError:没有这样的表:yourapp\u yourmodel。
是常见的 数据库中出现的错误不反映您的模型

如果您使用的是
django>=1.7
,那么您可能需要使用
python manage.py makemigrations yourapp
创建相应的迁移文件。
你可能会想读书。它也是一个非常有用的工具,可以管理数据库状态(添加模型、字段等),但有时要了解整个情况很难。

我也尝试过同样的方法。。使用假模型来持有额外权限。。我还有其他问题。。和你的不一样。。但是问题。。因此,我决定不顾一切地编写一些代码来显式地创建我的额外权限,并将这些代码放在我的库中:

from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission

def get_or_create_permission(codename, name, content_type):
    permission = Permission.objects.filter(content_type=content_type, codename=codename).first()

    if not permission:
        permission =  Permission.objects.create(content_type=content_type, codename=codename, name=name)
        print "Created Permission: %s in content type: %s" % (permission, content_type,)
    else:
        print "Found Permission: %s in ContentType: %s" % (permission, content_type,)

    return permission

def get_or_create_content_type(app_label, name, model):
      content_type = ContentType.objects.filter(app_label=app_label, model=model).first()
    if not content_type:
        content_type = ContentType.objects.create(app_label=app_label, model=model, name=name)
        print "Created ContentType: %s" % content_type
    else:
        print "Found ContentType: %s" % content_type

    return content_type
现在在您的url.py(或启动时将执行的任何其他地方)中确定:

这可以确保启动时您的权限在那里。有一天,我会做一个包装,这样我只需要通过一个许可字典,它会做一切在一个函数调用…< / P >高兴有帮助:)如果它解决了你的问题,你能考虑把我的答案标记为正确吗?
content_type = get_or_create_content_type('appname', 'Feeds', 'feeds')
get_or_create_permission('change_feed_defaults', 'Change Feed Defaults', content_type)
get_or_create_permission('view_logs', 'View Logs', content_type)
# etc