Pergunta

I do have the two models below. So I'm trying to get all the modules of a particular course. As you can see, I'm already getting that particular course. So I just need to get the modules from it. I read the docs about filtering a ManyToManyField but still couldn't make it work. I know that maybe it's too simple but can't solve it.

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")
Foi útil?

Solução

Try:

current_course = Course.objects.get(pk=course)
modules = Module.objects.all().filter(course=current_course)

Outras dicas

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
#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.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top