[Fixed]-Saving M2M relationship via inline formset

1👍

To manage your circular depencies, I recommend switching from:

class Contact(models.Model):
    ... (some other attributes)
    addresses = models.ManyToManyField(Address)

class Address(models.Model):
    ... (some attributes)
    contact = models.ForeignKey(Contact) # <- needed for inline formset

to:

class Contact(models.Model):
    ... (some other attributes)
    addresses = models.ManyToManyField('myapp.Address')

class Address(models.Model):
    ... (some attributes)
    contact = models.ForeignKey('myapp.Contact') # <- needed for inline formset

Do you see the difference in how I defined the relations? Rather than pass in a model class, I pass in the ‘string mapping’ for the model class. Then Django handles the rest.

This should handle your circular dependency issues. And might address any glitches had with formsets. However, as I tend to stay away from formsets I can’t say for certain.

Leave a comment