Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think what you want is to use an intermediary model to form the M2M relationship using the <code>through</code> keyword argument in the ManyToManyField. Sort of like the first answer above, but more "Django-y".</p> <pre><code>class A(models.Model): name = models.CharField(max_length=200) class B(models.Model): a = models.ManyToManyField(A, through='C') ... class C(models.Model): a = models.ForeignKey(A) b = models.ForeignKey(B) </code></pre> <p>When using the <code>through</code> keyword, the usual M2M manipulation methods are no longer available (this means <code>add</code>, <code>create</code>, <code>remove</code>, or assignment with <code>=</code> operator). Instead you must create the intermediary model itself, like so:</p> <pre><code> &gt;&gt;&gt; C.objects.create(a=a1, b=b) </code></pre> <p>However, you will still be able to use the usual querying operations on the model containing the <code>ManyToManyField</code>. In other words the following will still work:</p> <pre><code> &gt;&gt;&gt; b.a.filter(a=a1) </code></pre> <p>But maybe a better example is something like this:</p> <pre><code>&gt;&gt;&gt; B.objects.filter(a__name='Test') </code></pre> <p>As long as the FK fields on the intermediary model are not designated as <code>unique</code> you will be able to create multiple instances with the same FKs. You can also attach additional information about the relationship by adding any other fields you like to <code>C</code>. </p> <p>Intermediary models are documented <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany" rel="nofollow noreferrer">here</a>. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload