Django从Manager访问模型属性
我有以下型号:Django从Manager访问模型属性,django,django-managers,Django,Django Managers,我有以下型号: class Hospitalization(models.Model): patient = models.ForeignKey(Patient) room = models.ForeignKey(Room) date_in = models.DateField() date_out = models.DateField(blank=True, null=True) ... 我想列出目前的住院情况。所以我添加了一个@property'is
class Hospitalization(models.Model):
patient = models.ForeignKey(Patient)
room = models.ForeignKey(Room)
date_in = models.DateField()
date_out = models.DateField(blank=True, null=True)
...
我想列出目前的住院情况。所以我添加了一个@property'is_current':
@property
def is_current(self):
today = date.today()
if self.date_in and self.date_out:
if self.date_in <= today and self.date_out >= today:
return True
if self.date_in and not self.date_out:
if self.date_in <= today:
return True
但这也不起作用:*AttributeError:“HospitalizationManager”对象没有属性“date\u in”*
Django推荐的解决方法是什么 您的
经理有很多问题:
- 您正在子类化
模型
,而不是管理器
- 您正在使用模型属性,就好像它们属于
管理器,而它们不属于
- 您的自定义
get\u queryset
没有调用超类方法,因此它使用了未定义的qs
属性
定义经理的正确方法是:
class CurrentHospitalizationManager(models.Manager):
def get_query_set(self):
qs = super(CurrentHospitalizationManager, self).get_query_set()
today = date.today()
return qs.filter(
# we can use Q objects here to check if the date_out exists or not
# and compare against the current date if necesary
models.Q(date_out__isnull=True) | models.Q(date_out__gte=today),
date_in__lte=today
)
然后,您应该将管理器分配给模型上的class属性,如下所示
class Hospitalization(models.Model):
current_objects = CurrentHospitalizationManager()
...
并在代码中使用它,如下所示:
Hospitalization.current_objects.get(...) # or filter, or whatever
我不建议将此自定义管理器分配给默认的管理器属性(对象
),因为您将无法访问非“当前”的实例
如果定义中的date\u不能为空,那么中的self.date\u是否真的有必要使用Q对象,我能够实现我想要的。谢谢@asermax。谢谢你的评论。我以前从未与Q合作过。但是有些东西似乎不起作用:只要我在qs.filter()中组合“date_in_uulte=today”(如示例所示),那么在验证模型时就会得到“SyntaxError:non-keyword arg after-keyword arg”。问题似乎在于filter()中两个参数之间的逗号。我通过链接两个过滤器来修复它:return qs.filter(date\u in\u lte=today)。filter(models.Q(date\u out\u isnull=True)models.Q(date\u out\u gte=today))
。谢谢如果其他人也会有类似的问题,还有两个附加项:get\u queryset()
应该是get\u query\u set()
,而super(HospitalizationManager,self)
应该是super(CurrentHospitalizationManager,self)
。第一个问题可以通过像您那样链接过滤器或更改args的位置来解决(因为这毕竟是错误所在)。修复了答案中的问题,对此表示抱歉:]
Hospitalization.current_objects.get(...) # or filter, or whatever