Django self-relationship

Hello guys i want to add relationship in same model. For example there is a product model and i’ll have 1000+ product. And there will be level system between products.

So for real life example lets say there is 11 product with same property but different color and i want to choose one of 11 will to be big product and other 10 product will be baby product and when i listing products only big products will be shown, baby products will only be shown in big product’s detail page(For this product we have 5+ color and here images etc.).

Firstly i thought i can create same model twice and i can make relations but then i realized color thing won’t be only thing, there will be size, material etc thing and now i don’t know how can i start and which way i choose.

If it’s only two level and if there’s always two levels, I’d be inclined to look at a solution with three tables - one for “big” table, one for “baby” table - with an FK to “big”, and one for an “attributes table”. Each of “big” and “baby” would have an FK to “attributes”, and all the details would be stored in it.
How I would structure the “attributes table” might depend upon the number of attributes needing to be tracked and whether or not they’re universal across both “big” and “baby”. (But that’s really fodder for a different discussion.)

Not withstanding all of the above, the ForeignKey docs do describe how to define an FK relationship to self.

1 Like