| | 106 | |
|---|
| | 107 | # Adding via the 'other' end of an m2m |
|---|
| | 108 | >>> a4 = Article(headline='NASA finds intelligent life on Earth') |
|---|
| | 109 | >>> a4.save() |
|---|
| | 110 | >>> p2.article_set.add(a4) |
|---|
| | 111 | >>> p2.article_set.all() |
|---|
| | 112 | [NASA finds intelligent life on Earth] |
|---|
| | 113 | >>> a4.publications.all() |
|---|
| | 114 | [Science News] |
|---|
| | 115 | |
|---|
| | 116 | # Adding via the other end using keywords |
|---|
| | 117 | >>> a5 = p1.article_set.add(headline='Oxygen-free diet works wonders') |
|---|
| | 118 | >>> p2.article_set.all().order_by('headline') |
|---|
| | 119 | [NASA finds intelligent life on Earth, Oxygen-free diet works wonders] |
|---|
| | 120 | >>> a5.publications.all() |
|---|
| | 121 | [Science News] |
|---|
| | 122 | |
|---|
| | 123 | # Removing publication from an article: |
|---|
| | 124 | >>> a4.publications.remove(p2) |
|---|
| | 125 | >>> p2.article_set.all().order_by('headline') |
|---|
| | 126 | [Oxygen-free diet works wonders] |
|---|
| | 127 | >>> a4.publications.all() |
|---|
| | 128 | [] |
|---|
| | 129 | |
|---|
| | 130 | # And from the other end |
|---|
| | 131 | >>> p2.article_set.remove(a5) |
|---|
| | 132 | >>> p2.article_set.order_by('headline') |
|---|
| | 133 | [] |
|---|
| | 134 | >>> a5.publications.all() |
|---|
| | 135 | [] |
|---|
| | 136 | |
|---|
| | 137 | # You can clear the whole lot: |
|---|
| | 138 | # (put some back first) |
|---|
| | 139 | >>> p2.article_set.add(a4, a5) |
|---|
| | 140 | >>> a4.publications.add(p3) |
|---|
| | 141 | >>> a4.publications.order_by('title') |
|---|
| | 142 | [Science News, Science Weekly] |
|---|
| | 143 | >>> p2.article_set.clear() |
|---|
| | 144 | >>> p2.article_set.all() |
|---|
| | 145 | [] |
|---|
| | 146 | >>> a4.publications.all() |
|---|
| | 147 | [Science Weekly] |
|---|
| | 148 | |
|---|
| | 149 | # And you can clear from the other end |
|---|
| | 150 | >>> p2.article_set.add(a4, a5) |
|---|
| | 151 | >>> p2.article_set.all().order_by('headline') |
|---|
| | 152 | [NASA finds intelligent life on Earth, Oxygen-free diet works wonders] |
|---|
| | 153 | >>> a4.publications.order_by('title') |
|---|
| | 154 | [Science News, Science Weekly] |
|---|
| | 155 | >>> a4.publications.clear() |
|---|
| | 156 | >>> a4.publications.all() |
|---|
| | 157 | [] |
|---|
| | 158 | >>> p2.article_set.all().order_by('headline') |
|---|
| | 159 | [Oxygen-free diet works wonders] |
|---|
| | 160 | |
|---|
| | 161 | |
|---|
| | 162 | |
|---|