Django, queryset filter ManyToManyField

爷,独闯天下 提交于 2019-12-05 13:41:39

Try:

current_course = Course.objects.get(pk=course)
modules = Module.objects.all().filter(course=current_course)
#models.py
class Telephone(models.Model):
    status                = models.IntegerField(default=0)
    number                = models.CharField(max_length=255, blank=True)

class Profile(models.Model):
    first_name            = models.CharField(max_length=255, blank=True)
    last_name             = models.CharField(max_length=255, blank=True)
    telephone             = models.ManyToManyField(Telephone, blank=True, null=True)

#views.py
def api(request):
    profile = Profile.objects.get(pk=1) #just as an example
    primary_telephone     = profile.telephone.all().filter(status=1)

#I was looking for the primary telephone of my client, this was the way I have solved.

You have a related field on the Course model which is a M2M to Module and so this allows you to access the list of modules directly associated to a course.

Once you have the course simply fetch all of it's modules like so:

course = Course.objects.get(pk=course_id)
course_modules = course.modules.all()

I would always advise wrapping the first line that queries Course with a try/except - this is because the model manager's get method can throw an exception if a result cannot be found.

This can be done like so:

try:
    course = Course.objects.get(pk=course_id)
except Course.DoesNotExist:
    pass  # Handle this exception
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!