python – Django,queryset过滤ManyToManyField
作者:互联网
我确实有以下两种型号.所以我试图获得特定课程的所有模块.正如你所看到的,我已经得到了那个特定的课程.所以我只需要从中获取模块.我阅读了有关过滤ManyToManyField的the docs,但仍无法使其正常工作.我知道也许这太简单但无法解决.
models.py
class Course(models.Model):
name = models.CharField(max_length=100)
modules = models.ManyToManyField('Module', blank=True)
class Module(models.Model):
code = models.CharField(max_length=10, unique=True)
name = models.CharField(max_length=65)
year = models.IntegerField()
view.py
def ajax_get_modules(request, course):
current_course = Course.objects.get(pk=course).pk
modules = Module.objects.filter(...........)
if request.is_ajax():
data = serializers.serialize('json', modules)
return HttpResponse(data, content_type="application/javascript")
解决方法:
尝试:
current_course = Course.objects.get(pk=course)
modules = Module.objects.all().filter(course=current_course)
标签:python,django,filter,django-orm 来源: https://codeday.me/bug/20190624/1279034.html