给出两个简单的模型:
class Employee(Model):
user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)
class AttendanceLog(Model):
from_datetime = models.DateTimeField(_('from'))
to_datetime = models.DateTimeField(_('to'))
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, verbose_name=_('employee'))
我们可以很好地检索some_employee
的出勤日志:some_employee.attendancelog_set
。我们还可以在考勤日志(objects = AttendanceLogQuerySet.as_manager()
)中使用自定义查询集,例如:
class AttendanceLogQuerySet(models.QuerySet):
def today(self):
# returns logs that has to_datetime with today's date.
return self.filter(
to_datetime__date=date.today()
)
因此,我们可以通过以下方式检索员工的出勤率:some_employee.attendancelog_set.today()
问题是当我们尝试使用自定义管理器和自定义Queryset(objects = AttendanceLogManager()
)时,例如:
class AttendanceLogQuerySet(models.QuerySet):
def today(self):
# returns logs that has to_datetime with today's date.
return self.filter(
to_datetime__date=datetime.today()
)
class AttendanceLogManager(models.Manager):
def get_queryset(self):
return AttendanceLogQuerySet(self.model, using=self._db)
def some_special_create_method(self, some_args):
pass
我们收到错误消息:
AttributeError: 'RelatedManager' object has no attribute 'today'
根据documentation,这应该适用于如何使用QuerySet和Manager。
答案 0 :(得分:0)
在您的AttendanceLogManager类中,您应该定义:
def today(self):
return self.get_queryset().today()
在那之后,您需要在类AttendanceLog(Model)中声明:
objects = AttendanceLogManager()
我发现this link很有帮助