2015-09-10 63 views
1

我有兩個不同的模型,引用django User,即RecruiterUserprofileDjango:檢查哪個相關對象存在

我有一個函數接收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

您能否顯示Recruiter和Userprofile模型? – Joseph

+0

@Joseph:我已經更新了這個問題 – nish

回答

3

可以使用.exists()查詢集API,像這樣(假設user是用戶模型的實例,都USERPROFILE和招聘鍵與現場也被命名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