python - Django:检查存在哪个相关对象

标签 python django

我有两个引用 django User 的不同模型,即 RecruiterUserprofile

我有一个接收 User 对象作为参数的函数。我需要检查存在哪些相关对象并采取相应的措施。我正在使用嵌套的 try-catch 来执行此操作:

def some_function(user, ....):
    ...
    try:
        profile = user.userprofile
        profile.profile_pic.save('{0}_social.jpg'.format(user.username))
        profile.save()
    except:
        try:
            recruiter = user.recruiter
            recruiter.cover_pic.save('{0}_social.jpg'.format(user.username))
            recruiter.save()
        except:
            pass

是否有更好/更优雅的方式来做到这一点?

编辑:正在考虑的模型如下

class Recruiter(models.Model):
    user = models.OneToOneField(User, unique=True, related_name='recruiter')
    ...

class UserProfile(models.Model):
    user = models.OneToOneField(User, unique=True, related_name='userprofile')
    ...

最佳答案

您可以使用 .exists() QuerySet API,就像这样(假设 user 是 User 模型的一个实例,并且 Userprofile 和 Recruiter 键是该模型的一个字段也命名为 用户):

def some_function(user, ...):
    if Userprofile.objects.filter(user=user).exists()
        profile = user.userprofile
        profile.profile_pic.save('{0}_social.jpg'.format(user.username))
        profile.save()
    elif Recruiter.objects.filter(user=user).exists()
        recruiter = user.recruiter
        recruiter.cover_pic.save('{0}_social.jpg'.format(user.username))
        recruiter.save()
    else:
        # User has neither Userprofile nor Recruiter associated with it!
        # Do something here to handle that case, or just get rid of the else

请注意,.exists() 调用将首先查询对象是否存在,然后是访问该对象的行(例如,user.userprofile) 将运行另一个查询以实际访问该对象。一种稍微优化的方式可能是:

def some_function(user, ...):
    userprofiles = Userprofile.objects.filter(user=user)
    recruiters = Recruiter.objects.filter(user=user)
    if len(userprofiles):
        profile = userprofiles[0]
        profile.profile_pic.save('{0}_social.jpg'.format(user.username))
        profile.save()
    elif len(recruiters):
        recruiter = recruiters[0]
        recruiter.cover_pic.save('{0}_social.jpg'.format(user.username))
        recruiter.save()
    else:
        # User has neither Userprofile nor Recruiter associated with it!
        # Do something here to handle that case, or just get rid of the else

关于python - Django:检查存在哪个相关对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32511145/

相关文章:

python - 在保持图像纵横比的同时,在水平布局内调整像素图大小行为的标签不一致

python - 最快检查行是否以列表中的值开头?

django - 如何在保持本地化不变的情况下只覆盖 django 中的 DECIMAL_SEPARATOR?

django - 更改 Django 控制台日志级别的简洁方法

python - 尝试/异常(exception)错误Python?

python - 从 QListWidget 拖放到 QPlainTextEdit

python - 如何在不损失效率的情况下将这段代码变成 1 行代码?

django - pg_dump 与 Django : -o flag needed?

python - Django shell 命令更改 json 数据中的值

django - Heroku 未从 requirements.txt 安装 psycopg2