views:

108

answers:

1

Given a model like this:

class A(models.Model):
    def __unicode__(self):
        return "%d"%self.id

class B(models.Model):
    a_set = models.ManyToManyField(A)

    def __unicode__(self):
        return "%d"%self.id

Then the following series of operations demonstrates my problem:

In [1]: a1=A()
In [2]: a1.save()
In [3]: a1
Out[3]: <A: 1>

In [4]: b1=B()
In [5]: b1.save()
In [6]: b1
Out[6]: <B: 1>

In [7]: b2=B()
In [8]: b2.save()
In [9]: b2
Out[9]: <B: 2>

In [10]: a1.b_set.add(b1)
In [11]: a1.b_set.all()
Out[11]: [<B: 1>]

In [12]: a1.b_set.add(b2)
In [13]: a1.b_set.all()
Out[13]: [<B: 1>, <B: 2>]

In [14]: a1.b_set.add(b2)
In [15]: a1.b_set.all()
Out[15]: [<B: 1>, <B: 2>]

At the end there what I want to see is:

Out[15]: [<B: 1>, <B: 2>, <B: 2>]
+2  A: 

You can create a third table:

class JoinModel(models.Model):
    a = models.ForeignKey(A)
    b = models.ForeignKey(B)

I believe this will allow you to create any number of relationships between instances of A and B.

Michael Williamson
ok, that makes sense, but I have a few places where this occurs, so if there is a way of doing it without manually creating the relationship tables then that would be preferable
tolomea