我有两个模型,分别为 course 和 courseDate ,我希望根据下一个可用日期next_course_date
动态返回相关对象。
1个课程有很多 courseDates 。
这应该返回每个课程的下一个courseDate实例。
我必须为此创建一个Relationfield并使用方法更改值吗?
class Course(models.Model):
class Meta:
verbose_name = "Kurs"
verbose_name_plural = "Kurse"
uuid = models.UUIDField(default=uuid.uuid4, editable=False)
owner = models.ForeignKey(Company, related_name='courses', on_delete=models.DO_NOTHING)
name = models.CharField(max_length=60)
categories = models.ManyToManyField(Category, related_name='courses')
next_course_date = models.IntegerField(default=0)
access_level = models.IntegerField(default=1)
status = models.IntegerField(default=1)
published = models.BooleanField(default=False)
banner = models.URLField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class CourseDate(models.Model):
class Meta:
verbose_name = "Kurstermin"
verbose_name_plural = "Kursetermine"
uuid = models.UUIDField(default=uuid.uuid4, editable=False)
owner = models.ForeignKey(Company, related_name='course_dates', on_delete=models.DO_NOTHING)
course = models.ForeignKey(Course, on_delete=models.DO_NOTHING, related_name='course_dates')
lecturers = models.ManyToManyField(User, related_name='main_lecturers')
begin = models.DateTimeField()#not editable
end = models.DateTimeField()#not editable
date_details = models.DateTimeField(auto_now=True, auto_now_add=False)
access_level = models.IntegerField(default=1)
status = models.IntegerField(default=1)
published = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
答案 0 :(得分:1)
为什么不将属性添加到课程中以返回下一个可用日期?假设begin
字段定义了“下一个”课程:
from dateime import datetime
class Course(models.Model):
# your fields and meta
@property
def next_date(self):
return CourseDate.objects.filter(begin__gte=datetime.today()).order_by('begin').first()
我添加了一个过滤器,用于过滤过去的日期。对于每个Course
实例,course.next_date
会为您提供从今天开始的下一个CourseDate实例。
答案 1 :(得分:0)
ForeignKey关系很有意义,那么您可以使用Django查询自身来执行“跨越关系的查找”。
查看此链接: https://docs.djangoproject.com/en/3.0/topics/db/queries/#lookups-that-span-relationships
希望这会有所帮助