Skip to content
Advertisement

Foreign key relationship with boolean values

I’m working on a feature. I’ve three different car types (Sedan, Hatchback, SUV):

Category(models.Model):
    id-
    name-
    image-

I’ve 6 features in total.

Feature(models.Model):
    id-
    name-
    detail-
    image-

Out of 6, 4 features are their in every car. The second car category has 5 and the third has all the 6 features. Here where I’m getting stuck: I’ve to send all the 6 features in all the categories to the frontend so that if someone clicks on the first category, they should be able to show them all 6 with 2 non-available feature strike down or disabled or something. So basically there should be some boolean value which shows that this feature in this category is True or False.

How can I design the tables?

Advertisement

Answer

a n:m Many to many relationship is represented as bridge table

And this would look like(the modes are shortend)

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=30, db_index=True)


class Feature(models.Model):
    name = models.CharField(max_length=30, db_index=True)
    categories = models.ManyToManyField(Category, through='CategoryFeature')


class CategoryFeature(models.Model):
    feature= models.ForeignKey(Feature, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
5 People found this is helpful
Advertisement