Search code examples
pythondjangomany-to-many

many to many table in django without using manytomanyfield


rather than using the models.ManyToMany field in django

i just set up a intermediary field with a bunch of foreign keys.

is there any reason why this wouldn't work. I can't think of any but why not see if any of you have tried the same.

class Authorization(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE,
                             )
    permission = models.ForeignKey( 'venueadmin.Permissions', blank=True, null=True)

    #venue = models.ForeignKey(venue)   <-- commented out cause I haven't made the model its referencing yet.

Solution

  • That is exactly how ManyToMany relationships work, except few things to consider.

    First, you might want to check how Django generates ManyToManyField here. It does almost the same you did here.

    Now, before starting using separate model think about next things:

    • database constraint is missing. It means that there is no validation on what has been put in to the Authorization table as example - Duplicate rows;
    • there is no indexation which means that search will become slow once Authorization grows. Interesting enough I did not find it in Django, maybe nobody cares? Two columns table might not be so critical;
    • there is no reason to keep an authorization record for user with no permissions. What is the reason of setting permissions to NULL? Does it carry any useful information for DB administrator in future?