skip to Main Content

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


  1. I think you should use ManyToManyField. This will create many to many relationship between tables

    Sample code:

    class Category(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')
        categories = models.ManyToManyField(Category, verbose_name='Categoies)
    
    Login or Signup to reply.
  2. You don’t. A ForeignKey refers to (at most) one item, so one Categories for each Product.

    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]:

    class Category(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 Product(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')
        categories = models.ManyToManyField(Category, verbose_name='Categoies')
    

    Note: Normally a Django model is given a singular name [django-antipatterns], so Category instead of Categories.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search