匿名用户的外键 [英] ForeignKey to AnonymousUser

查看:29
本文介绍了匿名用户的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遵循此准则并避免可为空的ForeignKey.

I would like to follow this guideline and avoid a nullable ForeignKey.

我有django用户模型的ForeignKey.

I have a ForeignKey to the django User model.

如果我尝试将request.user存储在此模型的实例中,则会出现此错误:

If I try to store request.user in an instance of this model, I get this error:

ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser>>":
 "MyModel.user" must be a "User" instance.

我认为避免非条件数据模式(可空外键)是可行的.

I think it is feasible to avoid the non-conditionless data schema (nullable foreign key).

我该如何解决?

推荐答案

这些准则建议您创建一个反映匿名用户的用户实例.否则称为前哨值.您必须通过一些唯一的密钥(可能是用户名)来跟踪它.然后确保它存在,并且没有其他人实际使用该密钥创建过用户,否则会遇到其他问题.

Those guidelines suggest you create an instance of user that reflects an anonymous user. Otherwise known as a sentinel value. You'd have to keep track of it via some unique key, likely the username. Then make sure it exists and nobody else has actually created a user with that key otherwise you run into other problems.

但是,由于上述概述的问题,我不同意这些准则.如果您的数据模型允许可选关系,那么您绝对应该使用NULL值.

However, because of those outlined issues above I disagree with those guidelines. If your data model allows for optional relationships, then you absolutely should use NULL values.

关于评论:

如果您的数据中没有NULL,那么在处理数据时,您的源代码中就不会有NullPointerException:-)

If there is no NULL in your data, then there will be no NullPointerException in your source code while processing the data :-)

仅仅因为没有NULL字段,并不意味着这些条件不存在.您仍在处理这些极端情况,但更改名称和某些语法.您仍然容易受到错误的影响,因为您仍然有许多条件(而且鉴于现在必须确保您的哨兵值是唯一的,因此条件可能还会更多).

Simply because there are no NULL fields, doesn't mean those conditions don't exist. You still are handling these edge cases, but changing the names and some of the syntax. You're still vulnerable to bugs because you still have as many conditions (and potentially more given that you have to now make sure your sentinel value is unique).

这篇关于匿名用户的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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