将代理模型实例分配给外键 [英] Assigning a proxy model instance to foreign key

查看:51
本文介绍了将代理模型实例分配给外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django auth用户代理模型,该模型具有一些附加权限,如下所示:

I have a django auth user proxy model that has some extra permissions attached to it like so:

class User(User):
    class Meta:
        proxy = True
        permissions = (
            ("write_messages","May add new messages to front page"),
            ("view_maps","Can view the maps section"),
        )

在模型的其他地方,我有一个对象以User作为外键:

Elsewhere in the model I have an object that has User as a foreign key:

class Project(models.Model):
    creation_date   = models.DateTimeField(auto_now_add=True)
    modify_date     = models.DateTimeField(auto_now=True)
    owner           = models.ForeignKey(User)

在我的一种观点中,我尝试使用当前用户作为所有者来创建一个新项目

In one of my views I attempt to create a new project using the current user as the owner

@login_required
def new_project(request):
    project = Project.objects.create(owner=request.user)

但是,这将返回错误:

Cannot assign "<User: mwetter>": "Project.owner" must be a "User" instance.

我假设项目对象中的外键所有者引用的是Django User的基类,而不是我的代理类.有没有办法将我的代理用户称为外键?

I'm assuming that the foreign key owner in the project object is referring to the base class for Django User instead of my proxy class. Is there a way to refer to my proxy user as a foreign key instead?

推荐答案

为什么要调用代理类 User ,这肯定会导致该类与 django.contrib混淆.auth.models.User ?为什么不使用 UserProxy MyUser ?这样,无论何时使用它,都可以对其进行区分.

Why are you calling your proxy class User, which is guaranteed to lead to confusion between that and django.contrib.auth.models.User? Why not UserProxy, or MyUser? Then it could be distinguished whenever you use it.

这篇关于将代理模型实例分配给外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆