Monday, March 31, 2014

Re: ManyToMany quick question

On Monday, March 31, 2014 5:37:05 PM UTC-4:30, willyhakim wrote:
when creating your models, how do you know which field to assign the ManyToManyField ?

 from django.db import models

class Student(models.Model):
    name = models.TextField()

class Course(models.Model):
    name = models.TextField()
    students = models.ManyToManyField(Student, related_name='courses')

>>> from testapp import models
>>> a = models.Student(name='aaaaa')
>>> b = models.Student(name='bbbbb')
>>> c = models.Course(name='cccccccc')
>>> c.students.add(a)
>>> c.students.add(b)
>>> c.students.all()
[<Student: Student object>, <Student: Student object>]

>>> a = models.Student.objects.get(name='aaaaa')
[<Course: Course object>]

Is this what you are asking?

You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To post to this group, send email to
Visit this group at
To view this discussion on the web visit
For more options, visit

No comments:

Post a Comment