我有两个类似的模型,有一个公共管理器,它返回当前登录用户的查询集。我希望当引发DoesNotExist异常时,User_Places.current_user.get(place = XXX)返回现有的User_Place()对象或空User_Places()。这怎么可能?如果我是对的,CurrentUserManager对User_Places和User_Projects模型一无所知?
我只是不想写总是:
try:
places = User_Places.current_user.get(place=XXX)
except:
places = User_Places()
我的模特代码:
class User_Places(models.Model):
place = models.ForeignKey('Place')
user = models.ForeignKey(User)
current_user = CurrentUserManager()
class User_Projects(models.Model):
project = models.ForeignKey('Project')
user = models.ForeignKey(User)
current_user = CurrentUserManager()
class CurrentUserManager(models.Manager):
def get_query_set(self):
user = threadlocals.get_current_user()
qs = super(CurrentUserManager, self).get_query_set()
if user:
qs = qs.filter(user=user)
return qs
def get(self, *args, **kwargs):
try:
object = super(CurrentUserManager, self).get(*args, **kwargs)
except:
object = ????????????????????????
return object
答案 0 :(得分:2)
找到解决方案here。 Manager类中有self.model():
class CurrentUserManager(models.Manager):
....
def get(self, *args, **kwargs):
try:
object = super(CurrentUserManager, self).get(*args, **kwargs)
except:
object = self.model(**kwargs)
return object