Home > Blockchain >  How to create many to many relationships using three tables Django
How to create many to many relationships using three tables Django

Time:10-21

I have three tables Client, Company, Account and want to create a relation between then so that they can satisfy following conditions.

  1. One client can have many accounts. One Account can be associated with many clients.
  2. One company can have many accounts. One account can be in many companies.
  3. One client can have many companies. One Company can be associated with many clients.

Tables are as follows:

class Company(models.Model):
    name = models.CharField(max_length=255)
    website_url = models.CharField(max_length=255, null=True, blank=True, default='')

class Account(models.Model):
    customer_id = models.CharField(max_length=20, null=True, blank=True)
    name = models.CharField(max_length=255)

class Client(models.Model):
    name = models.CharField(max_length=255)
    age = models.CharField(max_length=10, null=True, blank=True)

I don't know how to define many to many relationships for these tables.

CodePudding user response:

Checkout this so answer: Understanding ManyToMany fields in Django with a through model

You can also look for django documentation about many to many fields : https://docs.djangoproject.com/en/4.1/topics/db/examples/many_to_many/

  • Related