How to automatically create symmetric object on Django's ManyToManyField?

Viewed 913

I want to create a symmetric relationship on my model and also add a field in the relationship. I came across this blog (and also this another blog) and followed the steps in creating my own models.

class CreditCardIssuer(models.Model):
    name = models.CharField(_('name'), max_length=256)
    transfer_limits = models.ManyToManyField('self', through='Balancetransfer', related_name='no_transfer_allowed+', symmetrical=False, help_text=_('List of issuers to which balance transfer is not allowed.'))

    def add_balancetransfer(self, creditcardissuer, until):
        balance_transfer, _newly_created = Balancetransfer.objects.get_or_create(
            no_transfer_from=self,
            no_transfer_to=creditcardissuer,
            until=until)
        balance_transfer, _newly_created = Balancetransfer.objects.get_or_create(
            no_transfer_from=creditcardissuer,
            no_transfer_to=self,
            until=until)
        return balance_transfer

    def remove_balancetransfer(self, creditcardissuer, until):
        Balancetransfer.objects.filter(
            no_transfer_from=self, 
            no_transfer_to=creditcardissuer,
            until=until).delete()
        Balancetransfer.objects.filter(
            no_transfer_from=self, 
            no_transfer_to=creditcardissuer,
            until=until).delete()
        return

    def get_transfer_limits(self, until):
        return self.transfer_limits.filter(
            no_transfer_to__until=until, 
            no_transfer_to__no_transfer_from=self)


class Balancetransfer(models.Model):
    no_transfer_from = models.ForeignKey('CreditCardIssuer', related_name='no_transfer_from')
    no_transfer_to = models.ForeignKey('CreditCardIssuer', related_name='no_transfer_to')
    until = models.IntegerField(blank=True, null=True, help_text='Minimum card ownership period to allow balance transfer.')

    class Meta:
        unique_together = ('no_transfer_from', 'no_transfer_to')

But when I create the relationship from admin, only one is created. Can you please help me figure out the problem?

1 Answers
Related