[Answered ]-Django ManyToManyField Foreign Key Design

2👍

✅

ContactNumberTypeField is not defined at the time of defining of Contact class. Change contact_no field to this:

class Contact(models.Model):
    ...
    contact_no = models.ManyToManyField('ContactNumberTypeField', 
                 through='ContactContactNumber',
                 through_fields=('contact_name','contact_type'))

Note the quotes around ‘ContactNumberTypeField’.

The other error here is the wrong order of field names in through_fields attribute of the ContactNumberTypeField.contact_no field. It should be:

class ContactNumberTypeField(models.Model):
    ...
    contact_no = models.ManyToManyField(Contact, 
                 through='ContactContactNumber',
                 through_fields=('contact_type','contact_name'))

Read the documentation about field1 and field2.

Leave a comment