There is a model:
class Categories(models.Model):
name = models.CharField(max_length=150, unique=True, verbose_name='Name')
slug = models.SlugField(max_length=200, unique=True, blank=True, null=True, verbose_name='URL')
class Products(models.Model):
name = models.CharField(max_length=150, unique=True, verbose_name='Name')
slug = models.SlugField(max_length=200, unique=True, blank=True, null=True, verbose_name='URL')
category = models.ForeignKey(to=Categories, on_delete=models.PROTECT, verbose_name='Categoy')
I don’t understand how to make it so that in Products I could write category_id separated by commas. That is, so that one product would have different categories. Are there any separator arguments for Foreignkey? For example, I will show my idea with pseudocode
category = models.ForeignKey(to=Categories, on_delete=models.PROTECT, separator=';')
2
Answers
I think you should use ManyToManyField. This will create many to many relationship between tables
Sample code:
You don’t. A
ForeignKey
refers to (at most) one item, so oneCategories
for eachProduct
.If you need zero, one, or more categories, you use a
ManyToManyField
[Django-doc], this works with a junction table [wiki], which is typically how you implement many-to-many relations in a relational database. This is indeed not a comma separated list, but that would probably not be a good idea anyway, since it essentially breaks first normal form (1NF) [wiki]: