Django模型用于像对象一样的时间表

时间:2015-06-03 18:35:47

标签: python django database

我必须实现一个时间表。它会像HTML中的表格一样显示。该表如下所示:


| Subject | Timing | Teacher |
|---      |---     |---      |
| Maths   | 9-10   | Abc     |
| English | 10-11  | Qwe     |
| Science | 11-12  | Zxc     |

我已经有through模型,其中包含此section模型。 time-table模型的教师也有section,其主题也有ManyToManyField

ManyToManyField

对于我创建以下模型的时间。

class Section(models.Model):
    subject = ManyToManyField(Subject)
    teacher = ManyToManyField(Teacher)
    time_table = ManyToManyField(TimeTable)

我第一次尝试创建时间表模型是:

class Timing(models.Model):
    time_start = models.TimeField()
    time_end   = models.TimeField()

是否有更好的实现来创建这些类型的表?

此外,我觉得我的时间表模型并不完美,因为我使用的不是将主题和教师选择限制在仅适用于该部分的那些。

1 个答案:

答案 0 :(得分:1)

这是我的实现方式

models.py

class TimeTable(models.Model):
    DAYS_OF_THE_WEEK = (
        ('1', 'Понедельник'),
        ('2', 'Вторник'),
        ('3', 'Среда'),
        ('4', 'Четверг'),
        ('5', 'Пятница'),
        ('6', 'Суббота'),
        ('7', 'Воскресеньe')
    )
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    day = models.CharField(max_length=1, choices=DAYS_OF_THE_WEEK)

    class Meta:
        verbose_name = 'Расписание'
        verbose_name_plural = 'Расписания'


class TimeTableItem(models.Model):
    time_table = models.ForeignKey(TimeTable, on_delete=models.CASCADE)
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
    teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
    start_time = models.TimeField()
    end_time = models.TimeField()

    def __str__(self):
        return 'Предмет:{}, Учитель:{}, Время:{}-{}'.format(self.subject, self.teacher, self.start_time, self.end_time)

    class Meta:
        ordering = ('start_time',)

admin.py

class TimeTableItemInline(admin.TabularInline):
    model = models.TimeTableItem
    raw_id_fields = ['subject']
    extra = 1


@admin.register(models.TimeTable)
class TimeTableAdmin(admin.ModelAdmin):
    list_display = ['course', 'day']
    inlines = [TimeTableItemInline]