[Answered ]-How should a many-to-many table be defined

1👍

(1) short answer: Yes this is normal.

Long answer: ManyToMany table will need a foreign key to both Category and GlobalPart tables. Strictly speaking those two foreign keys should be sufficient. The extra pk that you see in there is just for django magic. You can really get away with only those two foreign keys in that table if you manually define the many-to-many table yourself. However if you let django do it for you (by using ManyToManyField) you get this extra pk

(2) I suggest changing your model fields category_id to categories:

    class GlobalPart (Models.model):
        categories=models.ManyToManyField(Category, related_name = 'globalpart')

This is because, ManyToManyFields refers well to “many” items. This field does not refer to “one” category_id, it refers to all related categories. So when naming it would be natural to name it accordingly.

As for accessing all categories you can do it by accessing the “categories” property. Say if your object instance named global_part, you can access categories like this:

categories = global_part.categories.all()

Instead of all(), you can use filter() or exclude() the same way you use it when querying models.

Here is a link to related django docs

1👍

What do you think a foreign key is? It’s a field containing values that equate to IDs – usually primary keys – in the “foreign” table. If the other table has integer keys, as most Django tables do, then the foreign key field will be of type integer as well.

Additionally, Django creates constraints so that the database will enforce that the IDs do actually reference valid values in the foreign table. Depending on your database, these might or might not be displayed as part of the field definition.

Leave a comment