python - Django:按用户配置文件或外键过滤

标签 python django

对于帐户的简单激活 key ,我必须从随机数创建 key ,同时确保我没有使用与另一个帐户相同的 key 。现在,这就是我所拥有的:

def get_random_word():
    word = ''
    i = 0
    while i in range(10) and User.objects.filter(activation_key = word).exists():
        word += random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')
        i+=1
    return word

我现在意识到的问题是,我使用 django 的内置 User 类和这样的用户配置文件:

def create_user_info(sender, instance, created, **kwargs):
    if created:
        UserInfo.objects.create(user=instance)

post_save.connect(create_user_info, sender=User)


class UserInfo(models.Model):
    user = models.OneToOneField(User)
    pen_name = models.CharField(max_length=30)
    activated = models.BooleanField()
    activation_key = models.CharField(max_length=40)
    def __unicode__(self):
        return self.email + '-' + self.pen_name

我需要按用户个人资料进行过滤。因此,简而言之,我如何按键或更具体地说,按用户个人资料进行过滤。

最佳答案

首先,将 related_name 添加到您的用户信息中:

class UserInfo(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    ...

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name

然后你可以这样做:

User.objects.filter(profile__activation_key=word).exists()

希望对你有帮助:)

关于python - Django:按用户配置文件或外键过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11856519/

相关文章:

python - QTableModel 对齐标题

python - 如何在 Django 中翻译表单的标签和验证消息

python - 为 Django 创建一个保留顺序的多值字典

Django - 使用外键关系同时保存两条记录

python - 如何在浏览器和应用程序之间创建通信

python - 将两个排序列表合并为一个更大的排序列表

python - 如何使用 Python ctypes 表示打包的 Delphi 记录?

python - 使用 Enum 时 Admin 中的 Django 选择

django - 在 Django 模型迁移中,serialize=False 是什么意思?

python - pygccxml 在 python 3.0+ 或 Python 2.7+ 上?