I want to create a Category class that may or may not have a subcategory or it may or may not itself be a subclass of another Category object.
This doesn't work, but it gives an idea of what I'm trying to do:
class Category(models.Model):
about = models.TextField(blank=True)
parent_cat = models.ForeignKey(Category, blank=False, null=True)
slug = models.SlugField(unique=True, help_text = SLUG_HELP)
title = models.CharField(max_length = 26, unique=True)
...
What works right now is I have a SubCategory class that can relate to a Category. However I would like to make the code more flexible by just allow Categories to be sub-categories of themselves. Then I can have an unlimited number of parents/children. Can someone suggest how I might be able to do this?
To handle One-To-Many relationships in Django you need to use ForeignKey . The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).
To create a new instance of a model, instantiate it like any other Python class: class Model (**kwargs) The keyword arguments are the names of the fields you've defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save() .
CharField is a commonly-defined field used as an attribute to reference a text-based database column when defining Model classes with the Django ORM. The Django project has wonderful documentation for CharField and all of the other column fields.
In Django, a model is a class which is used to contain essential fields and methods. Each model class maps to a single table in the database. Django Model is a subclass of django. db.
Your reference to subclassing and inheritance is confusing. You've got a standard recursive relationship, which works fine via a ForeignKey. The only thing you'd need to do would be to define the FK as described in the documentation:
parent_cat = models.ForeignKey('self', blank=False, null=True)
What else "doesn't work" about the code you have posted?
You can use my model as an example. I use django-mptt to render a tree-listing view on the front end.
Including foreign key count in django mptt full tree listing?
class Category ( models.Model ):
name = models.CharField( max_length=100 )
parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
slug = models.SlugField(unique=True)
mptt.register(Category)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With