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')
>>> a.save()
>>> b = models.Student(name='bbbbb')
>>> b.save()
>>> c = models.Course(name='cccccccc')
>>> c.save()
>>> c.students.add(a)
>>> c.students.add(b)
>>> c.students.all()
[<Student: Student object>, <Student: Student object>]

>>> a = models.Student.objects.get(name='aaaaa')
>>> a.name
'aaaaa'
>>> a.courses.all()
[<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 django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/9e05634b-4784-4cfe-beb9-9e0a52218edb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment