如何将自定义字段添加到 Django 中的 auth_permission 模型?

How to add custom field to auth_permission model in django?

我正在使用 auth_permission 模型并在此模型中添加额外的字段。

class Permission(models.Model):

    name = models.CharField(_('name'), max_length=255)
    content_type = models.ForeignKey(
        ContentType,
        models.CASCADE,
        verbose_name=_('content type'),
    )
    codename = models.CharField(_('codename'), max_length=100)
    

我想添加的额外字段是

application_id = models.ForeignKey(ApplicationTbl, db_column='application_id', on_delete=models.CASCADE, blank=True, null=False)

有人可以告诉解决方法将其添加到 auth_permission 模型中。

给你的 models.py 放这个:

from django.contrib.auth.models import Permission

# inject application_id atribute to the Django Permission model
if not hasattr(Permission, 'application_id'):
    application_id = models.ForeignKey(ApplicationTbl, db_column='application_id', on_delete=models.CASCADE, blank=True, null=False)
    application_id.contribute_to_class(Permission, 'application_id')

之后,运行 迁移,您应该可以开始了。

official standard way in Django docs to do this is to define it in class Meta inside your model; which if it's your user model, you could also consider customizing it by using PermissionsMixin; 如果您将所有内容都放在正确的位置,我相信这也适用于您的情况。 您没有提供有关您的系统以及您正在尝试做什么的详细信息,但我猜您正在尝试弄清楚用户在哪个应用程序上下文中执行他的 activity。在这种情况下,如果您的系统规模相当大,您还可以尝试将用户身份验证后端视为 Django 项目中的一个单独的应用程序文件夹。希望我能帮到你。