如何使用 Django 智能选择来过滤 ManyToManyField?
class Course(models.Model):
course_code = models.CharField(max_length=100,unique=True)
title = models.CharField(max_length=200)
short = models.CharField(max_length=50)
elective_group = models.CharField(max_length=100)
class Unit(models.Model):
title = models.CharField(max_length=100)
short = models.CharField(max_length=50)
course = models.ForeignKey(Course)
class Pattern(models.Model):
pattern_name = models.CharField(max_length=200)
class ExamSchedule(models.Model):
exam_date = models.DateTimeField()
course = models.ForeignKey(Course)
pattern = models.ForeignKey(Pattern)
**units = models.ManyToManyField(Units)**
我需要实现类似用户创建 Examschedule 对象的功能,从下拉列表中选择课程后,单元小部件应该只包含与所选课程相关的单元。
谢谢 安克斯
class Course(models.Model):
course_code = models.CharField(max_length=100,unique=True)
title = models.CharField(max_length=200)
short = models.CharField(max_length=50)
elective_group = models.CharField(max_length=100)
class Unit(models.Model):
title = models.CharField(max_length=100)
short = models.CharField(max_length=50)
course = models.ForeignKey(Course)
class Pattern(models.Model):
pattern_name = models.CharField(max_length=200)
class ExamSchedule(models.Model):
exam_date = models.DateTimeField()
course = models.ForeignKey(Course)
pattern = models.ForeignKey(Pattern)
**units = models.ManyToManyField(Units)**
I need to implement functionality like if user creates an Examschedule object , after selecting a course from dropdown the unit widget should only contains those units that are related to the course selected.
Thanks
Anks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我用 Javascript 做了类似的事情。
首先禁用 Unit HTML 元素。用户选择课程后,系统会向服务器发送所选课程的 Ajax 请求,并返回有效的单位。仍然使用 Javascript,将这些单元添加到适当的元素,然后才启用它。如果用户更改课程,则会发出新请求以使用适当的单元更新单元元素。
为了加快速度,您可以向客户端提供所有单元,并在选择课程后使用 Javascript 动态加载它们。这种方法减少了等待时间,但增加了传输文件的大小(如果不是数百个,可能会更好)。
I've done something similar with Javascript.
Start with the Unit HTML element disabled. Once the user selects the course, an Ajax request is done to the server with the selected course and the valid units are returns. Still using Javascript you add those units to the appropriate element and only then enable it. If the user alters the Course a new request is done to update the Unit element with the appropriate units.
To speed up things, you can provide all the units to the client and also load them dynamically with Javascript once the Course is chosen. This approach reduces waiting time but increases the transfered file size (if they are not hundreds it's probably better).