我如何使用Django智能选择过滤ManyToManyField? [英] How can i use Django smart select to filter ManyToManyField?

查看:112
本文介绍了我如何使用Django智能选择过滤ManyToManyField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ = $ 200)
short = models.CharField(max_length = 50)
elective_group = models.CharField(max_length = 100)

类单位(models.Model):
title = models.CharField(max_length = 100)
short = models.CharField(max_length = 50)
course = models.ForeignKey(Course)

class模式(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对象的功能,在从下拉列表中选择课程后,单元小部件应该只包含与c相关的单元我们选择了。



感谢
Anks

解决方案

我已经做了类似于Javascript的事情。



从禁用单位HTML元素开始。一旦用户选择了课程,Ajax请求将通过所选课程对服务器进行,​​并返回有效单位。仍然使用Javascript,您将这些单位添加到适当的元素,然后才能启用它。如果用户更改课程,则会使用适当的单位更新Unit元素的新请求。



为了加快事宜,您可以向客户端提供所有单元并选择课程后,还可以使用Javascript动态加载它们。这种方法减少了等待时间,但增加了传输的文件大小(如果它们不是几百个可能更好)。


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

解决方案

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).

这篇关于我如何使用Django智能选择过滤ManyToManyField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆