DalinDad
DalinDad

Reputation: 103

Django - Get Variable in Junction Table - ManyToManyField

I use Django with a MySQL database and create my models with python manage.py inspectdb...but a well known problem is to manage junction table (n-n). Django propose ManyToManyField object but i stuck specific problem...

Models

class A(models.Model):
    id_A = models.AutoField(db_column='idA', primary_key=True)
    to_B = models.ManyToManyField(
        'B',
        through='A_has_B',
    )

class B(models.Model):
    id_B = models.AutoField(db_column='idB', primary_key=True)
    to_A = models.ManyToManyField(
        A,
        through='A_has_B',
    )

class A_has_B(models.Model):
    A_id_A = models.ForeignKey(A, models.DO_NOTHING, db_column='A_idA')
    B_id_B = models.ForeignKey(B, models.DO_NOTHING, db_column='B_idB')
    variable_i_want = models.CharField(db_column='variable_i_want', max_length=45)

Example case

I loop my A object model like this :

for a in A.objects.all():
    # Here i want to get the variable : variable_i_want
    variable_i_want = ?????????

Upvotes: 0

Views: 287

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47364

You can get all related A_has_B objects using reverse relation:

for a in A.objects.all():
    a_has_b_list = a.a_has_b_set.all()  # return all related objects
    for a_has_b in a_has_b_list:  
        variable_i_want = a_has_b.variable_i_want 

Note that A_id_A = models.ForeignKey(A, models.DO_NOTHING, db_column='A_idA') creates reverse relation manager which you can access from A object. By default name of this reverse relation attribute is lovercased model name appended with _set prefix a_has_v_set in your case. But you can control this name by using related_name argument.

Upvotes: 1

Related Questions