Python Django M2M attribute via an intermediary model

Viewed 32

I have a model with 2 M2M attributes: Connection is recursive and the ConnectionRequest uses an intermediary class. With Connection attribute, I am able to retrieve the connections of a user without problems (since I am using a native M2M field). But with ConnectionRequest is where I have challenges.

I would like to retrieve the 'connection requests' for this user but struggling with this natively. I have implemented it however programmatically (through a query) - but its not clean.

Basically, I would like to return the list of all connection requests. ie where the recipientAccount is the same as the parent class (Account) object.

class Account(models.Model):
    firstName = models.CharField(
        'First Name', max_length=100, blank=True, null=True)
    lastName = models.CharField(
        'Last Name', max_length=100, blank=True, null=True)
    emailAddress = models.EmailField(
        'Email Address', max_length=255, blank=True, null=True, unique=True)
    connections = models.ManyToManyField('self', blank=True)
    connection_requests = models.ManyToManyField(
        'ConnectionRequest', blank=True, related_name='accounts')

    def __str__(self):
        return self.firstName + ' ' + self.lastName

class ConnectionRequest(models.Model):
    senderAccount = models.ForeignKey(
        Account, related_name='sender_Account', on_delete=models.CASCADE)
    recipientAccount = models.ForeignKey(
        Account, related_name='recipient_Account', on_delete=models.CASCADE)

    def __str__(self):
        return str(self.senderAccount.id) + ' to ' + str(self.recipientAccount.id)

I have an idea to try the below but suddenly realised that I am unable to access the Account object from the ConnectionRequest class (since its a parent object/class).

class ConnectionRequest(models.Model):
    def __str__(self):
        return self.__class__.objects.filter(
            Q(recipientAccount=recipientaccount))

Should I be looking to implement this in the Account model? Perhaps as a method?

Thanks!

0 Answers
Related