Thursday, December 15, 2016

M2M Question

I have a Document model that has an M2M-symmetrical field on itself.  The idea is that we can “link” documents to other documents.  It’s very simple to find the linked documents of a particular document, but is there an easy way to get all the linked documents of the linked documents of the document in question?  I will probably have to write my own QuerySet or ModelManager function, but I was just curious if Django had something built in.

 

For example:

A is linked to J, C, K.

è J is linked to A

è C is linked to A

è K is linked to A

B is linked to J, M, P.

è J is linked to B

è M is linked to B

è P is linked to B

C is linked to O.

è O is linked to C

D is linked to O, P, R.

è O is linked to D

è P is linked to D

è R is linked to D

 

So when I get the entire “chain” of documents linked to A, I would get something like this:

J, C, K, B, O, D, P, R, M

 

Since J is linked to A and B, K is linked to A, and C is linked to A and O and O is linked to D, and D is linked to O and P, R is linked to D and P is linked to B which is linked to M (and J).

Hmmm…my contrived example exploded on me more than I intended…

No comments:

Post a Comment