Tyler Kim
Tyler Kim

Reputation: 379

Django model: set a "week of day" field as string from existing models.DateField()

I am trying to set a Session class's field based on another model Teacher's field. Basically, each Teacher has an assigned day of week (Monday, etc) and I want each Session object to have the Teacher.name as field based on Session's date field.

For example, Session class with the date=2021-12-25 would have the field weekday='Saturday' hence get a my_teacher_name='Mr.Saturday'

Since I need a string value such as "Monday" to query the teacher assigned to that day, I'm trying to figure out how to do this!

Here's the code:

from django.utils import timezone
from datetime import date, datetime

class Session(models.Model):
    class Timeblock(models.TextChoices):
        A = "8:00-8:20", "8:00-8:20"
        B = "8:20-8:40", "8:20-8:40"
        C = "8:40-9:00", "8:40-9:00"
        D = "9:00-9:20", "9:00-9:20"
        E = "9:20-9:40", "9:20-9:40"
        F = "9:40-10:00", "9:40-10:00"

    student = models.ForeignKey(User, on_delete=models.CASCADE)
    date_posted = models.DateTimeField(default=timezone.now)

    date = models.DateField()
    timeblock = models.CharField(max_length=10, choices=Timeblock.choices)
    helptype = models.CharField(max_length=50)
class Teacher(models.Model):
    class Weekday(models.TextChoices):
        mon = "Monday", "Monday"
        tue = "Tuesday", "Tuesday"
        wed = "Wednesday", "Wednesday"
        thu = "Thursday", "Thursday"
        fri = "Friday", "Friday"
        sun = "Sunday", "Sunday"

    name = models.CharField(max_length=50)
    email = models.CharField(max_length=50)
    expertise = models.CharField(max_length=100)
    assigned_day = models.CharField(max_length=10, choices=Weekday.choices)

    def __str__(self):
        return self.name

Here's what I've tried so far in Session class:

weekday = date.datetime.strftime("%A")
my_teacher = Teacher.objects.filter(assigned_day=weekday)
my_teacher_name = my_teacher.name

This raised the error: AttributeError: 'DateTimeField' object has no attribute 'datetime'

I'm also aware I can get week of day using {{ session.date|date:"F d - l" }} in templates but I am not sure how to actually use this as model's field and not just for display. Would appreciate any help!!

Upvotes: 2

Views: 990

Answers (1)

Tahseen Rahman
Tahseen Rahman

Reputation: 107

weekday = date_posted.datetime.strftime("%A") I think this is the culprit here. date_posted is already a datetime value and hence the error.

weekday = date_posted.strftime("%A") should be your solution.

Upvotes: 1

Related Questions