-1

Suppose I make a model:

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

Now after migration, this will create a table A_B with fields id,A_id,B_id. Now if I want to access the id of the table A_B, how to do that? And how to update the B_id of this table?

Priyansh Goel
  • 2,660
  • 1
  • 13
  • 37
  • Why would you need `B_id`? You can just access B from the otherside like B.col_set (or similar)? Can you give your models *actual* names, so we understand what you are trying to model? –  Mar 09 '15 at 09:24

2 Answers2

1

You are looking for Through Relationships

class A(models.Model):
       col = models.ManyToManyField(B, through='C')

class C(models.Model):
      a = models.ForeignKey(A)
      b = models.ForeignKey(B)
      //any other extra field

Then you can filter or query C table.

For example, to print all C instances id:

for c in C.objects.all():
     print c.id
GwynBleidD
  • 20,081
  • 5
  • 46
  • 77
levi
  • 22,001
  • 7
  • 73
  • 74
1

If you have an object of A:

A_obj.col.all()

This will return all the A_B objects related to that A

for ab in A_obj.col.all():
   print ab.id

This will print all the ids of the table A_B.

for ab in A_obj.col.all():
    ab.B_id = new id
    ab.save()

This will update your B_id with new id.

RéÑjïth
  • 458
  • 5
  • 13