Search code examples
djangomany-to-manybidirectional

How to get collection from both models in a bi-directional many-to-many relationship in django


I have two objects, Company and Account, in different packages. They have a many-to-many relation through employee, which has an additional field is_admin.

In Company I define the relation, and reading online, it seems that I don't have to redifine the relation in Account (this will result in a circular import).

Retrieving all the Accounts from the CompanySerializer is no problem, but I need to be able to get all the Companies registered to an account as well.

This is my thinking:

Account Model:

class Account(AbstractBaseUser):
current_jobs = models.ManyToManyField(
    Company, through='Employee') // I need to define current_jobs in some way
                                 //,but this results in circular import

Company Model:

class Company(models.Model):
employees = models.ManyToManyField(
    settings.AUTH_USER_MODEL, through='Employee')

Employee Model:

class Employee(models.Model):

class Meta:
    unique_together = ('user', 'company')


user = models.ForeignKey(settings.AUTH_USER_MODEL,
                         on_delete=models.CASCADE)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
is_admin = models.BooleanField()

The problem is, how will I now define how to get each of the lists in the serializers of the two. So the Company Serializer, and the Account Serializer...

If i do not define current_jobs, I get an error stating that current_jobs is not defined, which it ofcourse is not.


Solution

  • I don't understand why you think you need to define current_jobs on Account. That is automatically provided for you via the reverse relationship as company_set; if you need it to be current_jobs you can set the related_name attribute.