我有两个不同的模型引用了django User
,即Recruiter
和Userprofile
。
我有一个函数接收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')
...
答案 0 :(得分:4)
您可以像这样使用.exists()QuerySet API(假设user
是User模型的一个实例,Userprofile和Recruiter都是该模型的关键字,其字段也名为user
):
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