简体   繁体   中英

Python 3 Django Rest Framework - Manager object has no attribute error

I am trying to combine a filter on a custom property with a filter on a relationship in a custom manager, but keep running into the same error.

My custom EnrollmentManager says object has no attribute "end_date":

class EnrollmentManager(models.Manager):
  def org_students_enrolled(self, organisation):
    return self.filter(student__organisation__name=organisation).filter(self.end_date.date() >= datetime.date.today())

class Enrollment(TimeStampedModel):
  objects = EnrollmentManager()
  course = models.ForeignKey(to=Course, on_delete=models.CASCADE, default=None, null=False)
  student = models.ForeignKey(to=Student, on_delete=models.CASCADE, default=None, null=False)
  enrolled = models.DateTimeField()
  last_booking = models.DateTimeField()
  credits_total = models.SmallIntegerField(default=10)
  credits_balance = models.DecimalField(max_digits=5, decimal_places=2)

  @property
  def end_date(self):
    return self.enrolled + datetime.timedelta(days=182)

end_date is a custom property on Enrollment .

How can I use it in my manager to further filter the enrollments?

Model properties cannot be used to filter a queryset because those values (the end_date s) do not exist in the database, but instead they are derived from the data that is in the database (namely enrolled ). In order to achieve this you'll have to write your filter to use the data in the model fields like so:

class EnrollmentManager(models.Manager):
  def org_students_enrolled(self, organisation):
    return self.filter(student__organisation__name=organisation).filter(enrolled__gte=datetime.date.today() - datetime.timedelta(days=182))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM