Home > Software design >  Django Model M2M Relationship to 2 other models from the same model
Django Model M2M Relationship to 2 other models from the same model

Time:04-18

Here in my problem, I have a User model, in which a user (login) can be from the “Supplier” company or from “Customer” company.

It is a M2M relationship for both sets of tables: User-Customer and User-Supplier.

Can I link them this way:

company = models.ManyToManyField(Customer, Supplier, on_delete=models.PROTECT, related_name='Users')

enter image description here

Thanks!!

CodePudding user response:

You can't do that.

A better approach will be if you use a Company model with a type of Supplier and Customer you can create an enum for this because you are using the same fields in both of your models so its good to have a type in a single model.

How to make enum in model with TextChoices

Company:
     name
     address
     contact name
     type

then in your User model

company = models.ManyToManyField(Company, on_delete=models.PROTECT, related_name='Users')

make more sense this way.

  • Related