Django user authentication part 1

To define a many-to-many relationship, use ManyToManyField.

In this example, an SubChildCategory can be published in multiple Product objects, and a Product has multiple SubChildCategory objects:

Here is my models.py file…

from django.db import models

class SubChildCategory(models.Model):
    name=models.CharField(max_length=50, default=None)
    slug=models.SlugField(unique=True, max_length=50)
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at=models.DateTimeField(auto_now=True)  

    def __str__(self):
        return self.name
    
    def get_absolute_url(self):
        return reverse(kwargs={'slug':self.slug})

class Product(models.Model):
    name=models.CharField(max_length=225)
    slug=models.SlugField(max_length=225, unique=True)
    subcategory=models.ManyToManyField(SubChildCategory, verbose_name='Select Category')
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at=models.DateTimeField(auto_now=True)  

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('product_detail', kwargs={'slug':self.slug})

    #prepopulated_fields = {'slug': ('name',)}   (use this in admin.py file for auto slug when you type product name it will create auto slug)

    def image_tag(self):
            return mark_safe('<img src="/media/%s" width="70" height="70" />' % (self.thumb_image))

    image_tag.short_description = 'Image'

Now Run the makemigrations and migrate command from the terminal and it will create new table in your Database.

Now add product from your admin panel..

Also Read: How to Display ManyToMany relation data on view page?

Note: Feel free to ask any query in Comment section

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here