在 django 中存储带有昵称的匿名用户的优雅方法?
我的 django 应用程序中有一个简单的 Post 模型:
class Post(models.Model):
category = models.CharField(max_length=10, choices=choices)
message = models.CharField(max_length=500)
user = models.ForeignKey(User, editable=False)
我想实现让匿名用户使用昵称创建帖子的功能。不幸的是,django 不允许您将 AnonymousUser 实例保存为 Post 类的外键。
我正在考虑在数据库中添加一条“虚拟”用户记录,该记录代表匿名用户(id = 0,或者如果可能的话一些负数),该记录将用于没有用户的所有帖子。如果存在,则将使用可为空的名称字段来表示匿名用户的昵称。
这个解决方案对我来说似乎有点老套。有没有更清洁更有效的解决方案?
I have a simple Post model in my django app:
class Post(models.Model):
category = models.CharField(max_length=10, choices=choices)
message = models.CharField(max_length=500)
user = models.ForeignKey(User, editable=False)
I'd like to implement the feature of having anonymous users create posts with nick names. Unfortunately django doesn't allow you to save an instance of AnonymousUser as a foreignkey to the Post class.
I was thinking of adding a "dummy" user record into the db that represents the anonymous user(id=0, or some negative number if possible) that would be used for all posts without a user. And if it is present a nullable name field would be used to represent the nickname of the anonymous user.
This solution seems a bit hacky to me. Is there any cleaner more effecient solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您可以通过某些会话信息识别新用户,您可以创建普通用户帐户,形式可以这么说 - 带有一个标志将它们标识为易失性(这可能会导致一些定期维护清理) 。
如果在会话生命周期内,用户确实想要注册,您可以重复使用您这边的用户帐户,并且用户可以保留他的所有数据。
正如@slacy 评论和@Dominique 回答的那样;不要自己滚动查看现有项目,例如:
If you can identify new users by some session information, you could just create normal user accounts, pro forma so to speak - with a flag to identify them as volatile (this may lead to some regular maintenance cleanup).
If, during session lifetime, the user actually want to register, you can reuse the user account on your side and the user can keep all his data on his.
As @slacy commented and @Dominique answered; instead of rolling your own take a look at existing projects, e.g. this:
未经测试,但这可以帮助:
https://github.com/danfairs/django-lazysignup
Not tested , but this can help:
https://github.com/danfairs/django-lazysignup
您可以将
blank=True
和null=True
添加到User
ForeignKey
并将其设置为None< /code>,如果用户是匿名的。您只需将昵称存储在某个地方即可。
You can add
blank=True
andnull=True
toUser
ForeignKey
and set it toNone
, if user is anonymous. You just need to store the nickname somewhere.我是 Django 新手。一位朋友告诉我不要使用
ForeignKey
,进一步说明使用CharField
是可以的。ForeignKey
比CharField
慢,因为它对用户信息进行了一些检查。I am new to Django. A friend told me not to use
ForeignKey
further stating that usingCharField
is ok.ForeignKey
is slower thanCharField
, as it has some check for user info.