1

I'm trying to create a blog where one category may have some subcategory. I did this in my models.py

class Category(models.Model):
    title = models.CharField(max_length=50, unique=True)

    def __str__(self):
        return f"{self.title}"




class SubCategory(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    title = models.CharField(max_length=50, unique=True)

    def __str__(self):
        return f"{self.title}"

But I think It's not right to create two different class for the same task. So is there any other way to do it? Thank you.

Mahamudul Hasan
  • 301
  • 2
  • 5

2 Answers2

2

You could try using self-referencing ForeignKey.

class Category(models.Model):
    title = models.CharField(max_length=50, unique=True)
    parent_category = models.ForeignKey('self', related_name='sub_category')

    def __str__(self):
        return f"{self.title}"

Then it would work as something like:

 a_category = Category.objects.create(title='Parent category')
 Category.objects.create(title='subcategory', parent_category=a_category)

And to get all subcategories you would do:

a_category.sub_category.all()
Jonatas CD
  • 878
  • 2
  • 10
  • 19
0

Well, What you doing is not wrong, but if you want to do it on the same table you can use choice on charfield.

    YEAR_IN_SCHOOL_CHOICES = (
    (FRESHMAN, 'Freshman'),
    (SOPHOMORE, 'Sophomore'),
    (JUNIOR, 'Junior'),
    (SENIOR, 'Senior'),
    )
    sub_cat = models.CharField(choices=YEAR_IN_SCHOOL_CHOICES)

You can learn more about choices here

Bibek Bhandari
  • 422
  • 1
  • 4
  • 15