user4979733
user4979733

Reputation: 3411

How to link hierarhical data into another model in Django?

Consider the following hierarchical data. It can be 3 to 4 levels deep. I understand I can use existing packages like django-mptt or django-treebeard to create a tree data structure.

Now let's say I have another model called Battery. A battery can be compatible with multiple models for different market segments by different car vendors. So what I want to do is assign this battery to one or more compatible models above. I'm not sure how to accomplish this linkage in Django. Would it just be a ManytoMany field to the hierarchical model? Some pseudo-code would help.

class Battery(models.Model)
   name = Charfield(max_length=50)
   compatible_models = ????

I would also like to know how a query would be written. For example, I want to query all the battery that are compatible with ModelA by Mercedes, etc.

Upvotes: 0

Views: 63

Answers (1)

Damien Baldy
Damien Baldy

Reputation: 455

I think the below would work for you (in pure Django):

class CarBrand(models.Model):
    brand_name = models.CharField(...)
   
class CarType(models.Model):
    type_name = models.CharField(...)
    available_brands = models.ManyToManyField(CarBrand)

class ModelType(models.Model):
    model_name = models.CharField(...)
    available_car_types = models.ManyToManyField(CarType)

class BatteryType(models.Model):
    battery_name = models.CharField(...)
    supported_models = models.ManyToManyField(ModelType)

You would query Batteries as follows:

BatteryType.objects.filter(
supported_models__model_name='ModelA',supported_models__available_car_types__available_brands__brand_name='Mercedes'
)

Upvotes: 0

Related Questions