Thursday, December 8, 2022

Re: Django model design best practice guidance

On 9/12/2022 3:04 am, Joshua Corlin wrote:
Ive not used this field before so if it is im having a hard time wrapping my head around how this would work in this use case. 

Many-to-many is simple to conceptualise if you realise it is not a field in the table you think it is.

It is actually a separate table containing two foreign key fields. One points to a particular record in your target table and the other points to a particular target record in either the same table or a different table.

Django makes this easy by defining a many-to-many field in the model definition but it actually uses that definition to create the separate relationship table (the "through" table) with two foreign keys.

The nice thing is the "through" model can also be included explicitly among other model definitions. Doing so lets you add other fields to it which can describe the relationship.

It is definitely worthwhile studying the docs to get this right because it lets you model the real world much more accurately.

There are migration gotchas when you explicitly define models which have already been created implicitly with Django's many-to-many field but there are documented solutions.

Cheers

Mike

--   Signed email is an absolute defence against phishing. This email has  been signed with my private key. If you import my public key you can  automatically decrypt my signature and be sure it came from me. Just  ask and I'll send it to you. Your email software can handle signing.  

No comments:

Post a Comment